I have the following Python code:
>>> class My:
def __repr__(self):
return "My object"
def __str__(self):
return "My object"
>>> my = My()
>>> my.__repr__ = lambda: "I just changed repr"
>>> my.__repr__
<function <lambda> at 0x00000000033A91E0>
>>> repr(my)
'My object'
I can't understand why repr(my)
doesn't return the new value of __repr__
. I checked other functions and all of them worked the same way. It seems that Python checks the class first instead of checking whether the instance does have the required method.
Is it possible to override __repr__
in the instance level, without having to create a new class?