Is __mul__ sufficient for operator '*'?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Oct 20 08:52:06 CEST 2009


En Tue, 20 Oct 2009 00:59:12 -0300, Mick Krippendorf <mad.mick at gmx.de>  
escribió:
> Gabriel Genellina schrieb:

>> __special__ methods are searched in the type, not in the instance
>> directly. x*y looks for type(x).__mul__ (among other things)
>
> So I thought too, but:
>
> class meta(type):
>     def __mul__(*args):
>         return 123
>
> class boo(object):
>     __metaclass__ = meta
>
> print boo.__mul__
>
> b = boo()
> print b * 7
>
> also explodes. Or am I misinterpreting the word "type" here?

This is by design; see  
http://docs.python.org/reference/datamodel.html#special-method-lookup-for-new-style-classes

Methods defined on the meta-type aren't considered methods of the type;  
otherwise, every object would have the methods defined in `type` itself,  
because this is the metatype of every other object.

When I said "x*y looks for type(x).__mul__" the search for '__mul__' is  
done in type(x) itself, and all its base types along the MRO - NOT on the  
metatype, and not using getattr. There is no way to express this exact  
search in Python code (that I know of), but it's more or less like  
searching for '__mul__' in dir(type(x)).

In particular, __mul__ is stored in two slots (a slot is a field in a  
structure holding function pointers: nb_multiply in the tp_as_number  
structure, *and* sq_repeat in tp_as_sequence); defining or assigning to  
__mul__ "magically" updates those internal pointers. When executing x*y,  
__mul__ is retrieved directly from those pointers -- it is *not* searched  
by name.

In short, you have to define the __mul__ method on the type itself or any  
of its bases.

-- 
Gabriel Genellina




More information about the Python-list mailing list