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.