Why is __getattr__ capable of handling built-in operator overloads in Python 2.x but not in Python 3.x?

后端 未结 1 1213
南方客
南方客 2021-01-19 03:47

In python 2.x take the following class:

class Person:
    def __init__(self, name):
        self.name = name

    def myrepr(self):
        return str(self.n         


        
1条回答
  •  醉话见心
    2021-01-19 04:26

    It's not a Python 2 or 3 thing, it's a new-style vs old-style class thing. In old-style classes these methods had no special meaning, they were treated like simple attributes.

    In new-style classes the special methods are always looked up in the class(implicit lookup) not instance.

    For new-style classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary.

    Old-style classes:

    For old-style classes, special methods are always looked up in exactly the same way as any other method or attribute. This is the case regardless of whether the method is being looked up explicitly as in x.__getitem__(i) or implicitly as in x[i].

    Related: Overriding special methods on an instance

    0 讨论(0)
提交回复
热议问题