Home > Backend Development > Python Tutorial > Why Doesn\'t Overriding `__repr__` on an Instance Work in Python, and How Can It Be Effectively Achieved?

Why Doesn\'t Overriding `__repr__` on an Instance Work in Python, and How Can It Be Effectively Achieved?

Mary-Kate Olsen
Release: 2024-11-28 12:30:11
Original
670 people have browsed it

Why Doesn't Overriding `__repr__` on an Instance Work in Python, and How Can It Be Effectively Achieved?

Overriding Special Methods on an Instance

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>'
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template