__mul__ vs __rmul__ (and others) priority for different classes

Terry Reedy tjreedy at udel.edu
Fri Dec 11 15:24:02 EST 2009


dmitrey wrote:
> hi all,
> I have created a class MyClass and defined methods like __add__,
> __mul__, __pow__, __radd__, __rmul__ etc.
> Also, they are defined to work with numbers, Python lists and
> numpy.arrays.
> 
> Both Python lists and numpy arrays have their own methods __add__,
> __mul__, __pow__, __radd__, __rmul__ etc.
> If I involve myPythonList * myClassInstance it returns just result of
> my __rmul__; but when I invoke nuumpy_arr*myClassInstance it returns
> another numpy array with elements [nuumpy_arr[0]*myClassInstance,
> nuumpy_arr[1]*myClassInstance, ...].
> 
> Can I somehow prevent numpy array of using it __mul__ etc methods?
> (and use only my __rmul__, __radd__, etc instead)?

No. you have to put your class instance first to get priority.
Given a op b, python first calls a.__op__(b) and only if that fails, 
which it will for most builtin objects when b is MyClass, b.__rop__(a). 
Numpy arrays, however, are more broadminded about what they will work with.

If your operations are not commutative, you will either have to wrap 
numpy arrays in a class that disables the special methods or use 
explicit function calls.

Terry Jan Reedy




More information about the Python-list mailing list