Overriding special methods on an instance

后端 未结 5 1702
独厮守ぢ
独厮守ぢ 2020-11-22 03:36

I hope someone can answer this that has a good deep understanding of Python :)

Consider the following code:

>>> class A(object):
...     pas         


        
5条回答
  •  抹茶落季
    2020-11-22 03:52

    Python doesn't call the special methods, those with name surrounded by __ on the instance, but only on the class, apparently to improve performance. 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().

提交回复
热议问题