__getattribute__ for operators
Michael
gundlach at gmail.com
Sat Apr 18 13:29:01 EDT 2009
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?
If I manually define __add__(self, other) then "a + 2" will of course
use that method.
Michael
More information about the Python-list
mailing list