class TestClass:
def __init__(self):
pass
def __str__(self):
return 'You have called __str__'
def __repr__(self):
return 'You have called __repr__'
a = TestClass()
print(object.__repr__(a))
print(object.__str__(a))
Output:
<__main__.TestClass object at 0x7fe175c547c0>
You have called __repr__
What does those two functions do?
My understanding is that calling str(a)
returns a.__str__()
and calling repr(a)
returns a.__repr__()
. print(a)
also prints the string, a.__str__()
since there is an implicit str(a)
conversion going on.
Note that my question is not a duplicate to another popular question; see my first comment below.
The behaviour is COUNTERINTUITIVE; doing print(object.__str__(a))
prints the repr string instead of the str string.
CodePudding user response:
The object
class provides default implementations for the __repr__
and __str__
methods.
object.__repr__
displays the type of the object and itsid
(the address of the object in CPython)object.__str__(a)
callsrepr(a)
. The rationale is that if__str__
is not overriden in a classstr(a)
will automatically callrepr(a)
, using a possible override of__repr__
This is exactly what happens here because you are directly calling object.__str__
while this is not expected.