当我尝试 print
一个类的实例时,我得到如下输出:
>>> class Test():
... def __init__(self):
... self.a = 'foo'
...
>>> print(Test())
<__main__.Test object at 0x7fc9a9e36d60>
如何定义类及其实例的 _打印行为_(或 _字符串表示形式_)?例如,参考上面的代码,如何修改 Test
类,使 print
实例显示 a
值?
原文由 Ashwin Nanjappa 发布,翻译遵循 CC BY-SA 4.0 许可协议
__str__
方法是在打印时发生的调用,而__repr__
方法是在使用repr()
函数时发生的(或查看它与交互式提示)。如果没有给出
__str__
方法,Python将打印__repr__
的结果。 If you define__str__
but not__repr__
, Python will use what you see above as the__repr__
, but still use__str__
for printing.