Making special method names, work with __getattr__

Chris Rebert clp2 at rebertia.com
Mon Apr 26 13:14:36 CEST 2010


On Mon, Apr 26, 2010 at 3:57 AM, Antoon Pardon <apardon at forel.vub.ac.be> wrote:
> Op 2010-04-23, Chris Rebert schreef <clp2 at rebertia.com>:
>> On Fri, Apr 23, 2010 at 2:41 AM, Antoon Pardon <apardon at forel.vub.ac.be> wrote:
>>> The result I get is:
>>>
>>> 5
>>> 8
>>> 15
>>> Traceback (most recent call last):
>>>  File "Symbolics", line 54, in <module>
>>>    test()
>>>  File "Symbolics", line 51, in test
>>>    product = val1 * 7
>>> TypeError: unsupported operand type(s) for *: 'Symbol' and 'int'
>>>
>>> What I had hoped for was, that the line:
>>>
>>>  product = val1 * 7
>>>
>>> would be translated into something like
>>>
>>>  product = val1.__mul__(7)
>>
>> That's basically correct.
>>
>>> which would then be treated by the __getattr__ of the Expression superclass.
>>>
>>> That doesn't seem to happen.
>>
>> Indeed it doesn't. The lookup of fouble-underscore special methods
>> bypasses __getattribute__() and friends. For details, see
>> http://docs.python.org/reference/datamodel.html#special-method-lookup-for-new-style-classes
>
> This doesn't seem to be the whole picture.
>
> If I replace the line:
>
>  product = val1 * 7
>
> with
>
>  product = val1.__mul__(7)
>
> The code works.
>
> So the problem is not that the lookup for special methods is different.
> It seems that the lookup for special methods differ depending on wether they are
> called implicitly or explicitly.

I suppose that's true. Only a minor detail in practice though, as
__double_underscore__ methods are seldom (though not never) called
explicitly.

Cheers,
Chris



More information about the Python-list mailing list