Overriding special methods on an instance

后端 未结 5 1771
独厮守ぢ
独厮守ぢ 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 04:10

    The reason for this is special methods (__x__()) are defined for the class, not the instance.

    This makes sense when you think about __new__() - it would be impossible to call this on an instance as the instance doesn't exist when it's called.

    So you can do this on the class as a whole if you want to:

    >>> A.__repr__ = __repr__
    >>> a
    A
    

    Or on an individual instance, as in kindall's answer. (Note there is a lot of similarity here, but I thought my examples added enough to post this as well).

提交回复
热议问题