Skip to content Skip to sidebar Skip to footer

Why Is __getattr__ Capable Of Handling Built-in Operator Overloads In Python 2.x But Not In Python 3.x?

In python 2.x take the following class: class Person: def __init__(self, name): self.name = name def myrepr(self): return str(self.name) def __getattr

Solution 1:

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

Post a Comment for "Why Is __getattr__ Capable Of Handling Built-in Operator Overloads In Python 2.x But Not In Python 3.x?"