Python:恢复默认__str__行为

6 投票
2 回答
1083 浏览
提问于 2025-04-15 14:06

如果一个类里面没有定义__str__这个方法,Python会用什么默认的方式来显示这个类的对象呢?

class A :
   def __str__(self) :
      return "Something useless"

class B(A) :
   def __str__(self) :
      return some_magic_base_function(self)

2 个回答

2

如果一个类没有定义__str__这个方法,Python默认会使用repr这个方法来处理。

class B(A) :
   def __str__(self) :
      return repr(self)

这个规则适用于无论__repr__在继承链中是否被重写。换句话说,如果你想要跳过可能存在的__repr__的重写(而不是像这个方法那样使用它们),你就需要明确调用object.__repr__(self)(或者像另一个答案提到的调用object.__str__,效果是一样的)。

12

你可以使用 object.__str__() 这个方法:

class A:
   def __str__(self):
      return "Something useless"

class B(A):
   def __str__(self):
      return object.__str__(self)

这样可以得到 B 类实例的默认输出:

>>> b = B()
>>> str(b)
'<__main__.B instance at 0x7fb34c4f09e0>'

撰写回答