Python:恢复基础__str__行为

Pau*_*jan 6 python string

如果没有__str__方法,如何恢复python使用的默认函数?

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

class B(A) :
   def __str__(self) :
      return some_magic_base_function(self)
Run Code Online (Sandbox Code Playgroud)

sth*_*sth 12

你可以使用object.__str__():

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

class B(A):
   def __str__(self):
      return object.__str__(self)
Run Code Online (Sandbox Code Playgroud)

这为您提供了以下实例的默认输出B:

>>> b = B()
>>> str(b)
'<__main__.B instance at 0x7fb34c4f09e0>'
Run Code Online (Sandbox Code Playgroud)