如何使用print()打印类对象?我在学习Python的诀窍。当我试图打印类的对象时Foobar使用print()函数,得到如下输出:<__main__.Foobar instance at 0x7ff2a18c>有什么方法我可以设置印刷行为(或字符串表示)班级,等级及其对象?例如,当我打电话print()在类对象上,我想以某种格式打印其数据成员。如何在Python中实现这一点?如果您熟悉C+类,则可以实现上述标准ostream通过添加friend ostream& operator << (ostream&, const Foobar&)方法。
3 回答

撒科打诨
TA贡献1934条经验 获得超2个赞
>>> class Test:... def __repr__(self):... return "Test()"... def __str__(self):... return "member of Test"... >>> t = Test()>>> tTest()>>> print(t)member of Test
__str__
__repr__
repr()
__str__
__repr__
__str__
__repr__
__repr__
__str__

红颜莎娜
TA贡献1842条经验 获得超12个赞
__repr__
repr()
:
对于许多类型,此函数尝试返回一个字符串,该字符串将在传递给 eval()
否则,表示形式是一个括在尖括号中的字符串,该字符串包含对象类型的名称以及其他信息(通常包括对象的名称和地址)。类可以通过定义 __repr__()
方法。
class Test: def __init__(self, a, b): self.a = a self.b = b def __repr__(self): return "<Test a:%s b:%s>" % (self.a, self.b) def __str__(self): return "From str method of Test: a is %s, b is %s" % (self.a, self.b)
>>> t = Test(123, 456)>>> t<Test a:123 b:456>>>> print repr(t)<Test a:123 b:456>>>> print(t)From str method of Test: a is 123, b is 456 >>> print(str(t))From str method of Test: a is 123, b is 456
__str__
print(t)
print(str(t))
__repr__
__repr__
def __repr__(self): return "<%s instance at %s>" % (self.__class__.__name__, id(self))
添加回答
举报
0/150
提交
取消