Home >Backend Development >Python Tutorial >Why Doesn\'t Overriding `__repr__` on an Instance Work in Python, and How Can It Be Effectively Achieved?
Consider the code snippet below:
class A(object): pass def __repr__(self): return "A" from types import MethodType a = A() print(a) # <__main__.A object at 0x00AC6990> print(repr(a)) # '<__main__.A object at 0x00AC6990>' setattr(a, "__repr__", MethodType(__repr__, a, a.__class__)) print(a) # <__main__.A object at 0x00AC6990> print(repr(a)) # '<__main__.A object at 0x00AC6990>'
As observed, the custom __repr__ method is not called on the instance a. To understand this behavior, it's essential to note that:
In CPython (the standard Python interpreter), special methods with names surrounded by __ are typically not invoked on instances but rather on classes. As a result, attempting to override __repr__ directly on an instance will not yield the expected outcome.
To work around this limitation, one can leverage the following strategy:
class A(object): def __repr__(self): return self._repr() def _repr(self): return object.__repr__(self)
Here, __repr__ calls a helper method _repr, which then calls the default __repr__ implementation for the object class. By overriding _repr, we can effectively override __repr__ on an instance.
The above is the detailed content of Why Doesn\'t Overriding `__repr__` on an Instance Work in Python, and How Can It Be Effectively Achieved?. For more information, please follow other related articles on the PHP Chinese website!