本帖最后由 阿奇_o 于 2021-12-25 14:21 编辑
交互模式下(IDLE的shell,IPython,Jupyter等),对于类的对象实例,会自动调用 对象实例的 __repr__() 方法。(若没定义__repr__,则"回显"不太易读的代表该对象的"特殊字符形式")
对于函数(也是"对象"),则直接回显函数的返回值。这其实和调用类的实例的__repr__方法,并返回其结果,本质是一样的。
非交互模式下,通常需要通过打印其他绑定的变量,或借助其他函数,才能"打印"出对象的"回显信息",这时调用的是__str__方法。
如 借助print函数,print(obj) 实际打印的是obj.__str__() 的返回结果。
- >>> class Test():
- def __str__(self):
- return "from __str__"
- def __repr__(self):
- return "from __repr__"
-
- >>> t = Test()
- >>> t
- from __repr__
- >>> print(t)
- from __str__
- >>> t.__str__()
- 'from __str__'
- >>>
- >>> class Test():
- def __str__(self):
- return "from __str__"
-
- >>> t
- <__main__.Test object at 0x000001D7BD6D5AC8>
- >>>
复制代码