>>>>> Michael <gundl...@gmail.com> (M) wrote:

>M> While thinking about Steven D'Aprano's thread about automatically
>M> generating arithmetic operations for a subclass, I stumbled upon
>M> something confusing.  Having defined the following class to do funky
>M> addition,

>M> class MyInt(int):
>M>     def __getattribute__(self, key):
>M>         if key == "__add__":
>M>             print("In __getattribute__('__add__')")
>M>             return lambda other: MyInt(int.__add__(self, other+100))
>M>         else:
>M>             return object.__getattribute__(self, key)

>M>     def __getattr__(self, key):
>M>         if key == "__add__":
>M>             print("In __getattr__('__add__')")
>M>             return lambda other: MyInt(int.__add__(self, other+100))
>M>         else:
>M>             return object.__getattr__(self, key)

>M> I then do this:

>>>>> a = MyInt(4)
>>>>> a.__add__(2)
>M> In __getattribute__('__add__')
>M> 106
>>>>> a + 2
>M> 6
>>>>> 

>M> Why doesn't "a + 2" look up the __add__ attribute and use my lambda?
>M> If I manually define __add__(self, other) then "a + 2" will of course
>M> use that method.

This has just been discussed in the thread "Overriding methods
per-object". In short: In newstyle classes these methods when invoked
implicitely, e.g by a+2, are only looked up in the class, and bypass
__getattribute__.

See 
http://docs.python.org/reference/datamodel.html#special-method-lookup-for-new-style-classes
-- 
Piet van Oostrum <p...@cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to