Where is python getting the repr which is still yielding 'foo' even after the original repr method has been overwritten?
class Test(object):
def __init__(self, name, number_array):
self.name = name
self.number_array = number_array
def __repr__(self):
return str(self.name)
def custom_repr(self):
return str(self.name*4)
>>> A = Test('foo', [1,2])
>>> A
foo
>>> A.__repr__ = custom_repr.__get__(A, A.__class__)
>>>A.__repr__()
foofoofoofoo
>>>A
foo
According to the official documentation, __repr__ is used to compute the “official” string representation of an object and is typically used for debugging.
Python repr() Function returns a printable representation of an object in Python.
Definition. The Python repr() built-in function returns the printable representation of the specified object as a string.
As explained in Special Method Lookup:
For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary … In addition to bypassing any instance attributes in the interest of correctness, implicit special method lookup generally also bypasses the
__getattribute__()
method even of the object’s metaclass
(The part I've snipped out explains the rationale behind this, if you're interested in that.)
Python doesn't document exactly when an implementation should or shouldn't look up the method on the type; all it documents is, in effect, that implementations may or may not look at the instance for special method lookups, so you shouldn't count on either.
But, as you can guess from your test results, in the CPython implementation, __repr__
is one of the functions looked up on the type.
__repr__
is looked up directly on the class, not on the instance, when it's looked up by repr
or similar (such as when it's called by the interactive interpreter). If you must monkey-patch a repr, do it on the class (but please don't).
This same basic rule applies to most dunder methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With