[Python-Dev] __str__ does not default to __repr__ if a base class has __str__

Nick Coghlan ncoghlan at iinet.net.au
Wed May 19 21:48:33 EDT 2004


Guido van Rossum wrote:
>>class X(object):
>>    def __str__(self):
>>        return 'str for X'
>>
>>    def __repr__(self):
>>        return 'repr for X'
>>
>>class A(X):
>>    def __repr__(self):
>>        return 'repr for A'
>>
>>#    __str__ = __repr__
> 
> This has never been different and the current outcome is exactly what
> was intended.  The only case where __repr__ and __str__ act as each
> other's default is when there's no base class.

The OP's example also shows how easy it is to create a class which 
returns the same thing for str(foo) and repr(foo). Simply write one of 
either __repr__ or __str__ and then assign the same function to the 
other one.

Regards,
Nick.

-- 
Nick Coghlan               |     Brisbane, Australia
Email: ncoghlan at email.com  | Mobile: +61 409 573 268




More information about the Python-Dev mailing list