如何使用 print() 打印类的实例?

新手上路,请多包涵

当我尝试 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 许可协议

阅读 1.3k
2 个回答
>>> class Test:
...     def __repr__(self):
...         return "Test()"
...     def __str__(self):
...         return "member of Test"
...
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test

__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.

原文由 Chris Lutz 发布,翻译遵循 CC BY-SA 4.0 许可协议

正如 Chris Lutz 解释 的那样,这是由类中的 __repr__ 方法定义的。

来自 repr() 的文档:

对于许多类型,此函数会尝试返回一个字符串,该字符串在传递给 eval() 时会产生具有相同值的对象,否则表示形式是包含在尖括号中的字符串,其中包含类型的名称对象连同附加信息,通常包括对象的名称和地址。类可以通过定义 __repr__() 方法来控制此函数为其实例返回的内容。

给定以下类测试:

 class Test:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return f"<Test a:{self.a} b:{self.b}>"

    def __str__(self):
        return f"From str method of Test: a is {self.a}, b is {self.b}"

..它将在 Python shell 中执行以下操作:

 >>> 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

If no __str__ method is defined, print(t) (or print(str(t)) ) will use the result of __repr__ instead

如果 __repr__ 方法,则使用默认值, 大致相当于

 def __repr__(self):
    cls = self.__class__
    return f"<{cls.__module_}.{cls.__qualname__} object at {id(self)}>"

原文由 dbr 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题