__getattribute__ for operators

Terry Reedy tjreedy at udel.edu
Sat Apr 18 22:33:01 CEST 2009


Michael wrote:
> While thinking about Steven D'Aprano's thread about automatically
> generating arithmetic operations for a subclass, I stumbled upon
> something confusing.  Having defined the following class to do funky
> addition,
> 
> class MyInt(int):
>     def __getattribute__(self, key):
>         if key == "__add__":
>             print("In __getattribute__('__add__')")
>             return lambda other: MyInt(int.__add__(self, other+100))
>         else:
>             return object.__getattribute__(self, key)
> 
>     def __getattr__(self, key):
>         if key == "__add__":
>             print("In __getattr__('__add__')")
>             return lambda other: MyInt(int.__add__(self, other+100))
>         else:
>             return object.__getattr__(self, key)
> 
> I then do this:
> 
>>>> a = MyInt(4)
>>>> a.__add__(2)
> In __getattribute__('__add__')
> 106
>>>> a + 2
> 6
> 
> Why doesn't "a + 2" look up the __add__ attribute and use my lambda?

Answer 1: because it was not programmed that way ;-).

Answer 2: because __getattribute__/__getattr__ are for looking up 
attributes of instances of the class, whereas special methods are 
generally required to be attributes of the class.  So *their* lookup 
would use type(MyInt).__getxxx__.  When that fails, the add code looks 
for int.__radd__.  (I *think* this your answer.)

 > If I manually define __add__(self, other) then "a + 2" will of course
> use that method.

because that is that type(MyInt).__getxxx__ will find.

tjr




More information about the Python-list mailing list