Overriding special methods on an instance

Python usually doesn’t call the special methods, those with name surrounded by __ on the instance, but only on the class. (Although this is an implementation detail, it’s characteristic of CPython, the standard interpreter.) So there’s no way to override __repr__() directly on an instance and make it work. Instead, you need to do something like so:

class A(object):
    def __repr__(self):
        return self._repr()
    def _repr(self):
        return object.__repr__(self)

Now you can override __repr__() on an instance by substituting _repr().

Leave a Comment