__mul__ vs __rmul__ (and others) priority for different classes

D

dmitrey

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)?

Thank you in advance, D.
 
T

Terry Reedy

dmitrey said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top