Python:恢复为基__str__行为

问题描述:

如何恢复到python使用的默认函数,如果没有__str__方法?Python:恢复为基__str__行为

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

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

您可以使用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>' 

“的默认功能Python使用,如果没有__str__方法“是repr,所以:

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

这是否会在继承链中覆盖__repr__。 IOW,如果您还需要绕过__repr__(如果存在这些方法,请使用它们),您需要明确调用object.__repr__(self)(或object.__str__作为另一个建议 - 同样的事情)。