How can I revert back to the default function that python uses if there is no __str__
method?
class A :
def __str__(self) :
return "Something useless"
class B(A) :
def __str__(self) :
return some_magic_base_function(self)
How can I revert back to the default function that python uses if there is no __str__
method?
class A :
def __str__(self) :
return "Something useless"
class B(A) :
def __str__(self) :
return some_magic_base_function(self)
You can use object.__str__()
:
class A:
def __str__(self):
return "Something useless"
class B(A):
def __str__(self):
return object.__str__(self)
This gives you the default output for instances of B
:
>>> b = B()
>>> str(b)
'<__main__.B instance at 0x7fb34c4f09e0>'
"the default function that python uses if there is no __str__
method" is repr
, so:
class B(A) :
def __str__(self) :
return repr(self)
This holds whether __repr__
has been overridden in the inheritance chain or not. IOW, if you ALSO need to bypass possible overrides of __repr__
(as opposed to using them if they exist, as this approach would do), you will need explicit calls to object.__repr__(self)
(or to object.__str__
as another answer suggested -- same thing).