when 'myArray * 'myObject' is not equal to 'myObject' * 'myArray'

Nobody nobody at nowhere.com
Wed Aug 18 22:03:19 CEST 2010


On Wed, 18 Aug 2010 05:56:27 -0700, Duim wrote:

> Although I'm sure somewhere this issue is discussed in this (great)
> group, I didn't know the proper search words for it (although I
> tried).
> 
> I'm using python (2.6) scientifically mostly, and created a simple
> class to store time series (my 'Signal' class).
> I need this class to have a possibility to get multiplied by an array,
> but pre and post multiplication have different mathematical outcomes
> ( basically A* B != B*A ) .
> 
> Post multiplication by an array works fine defining __mul__ in the
> Signal class, but pre multiplication does not. It keeps trying to
> multiply all elements separately instead to send this array to my
> __rmul__ function.
> 
> How can I fix this without the need for a separate
> 'multiplysignal(A,B)' function?

Make Signal a subclass of numpy.ndarray. If one operand is a subclass of
the other, its __rmul__ will be preferred to the parent's __mul__.

In the absence of a subclass-superclass relationship, the LHS's __mul__ is
preferred to the RHS's __rmul__, so the RHS's __rmul__ is only called if
the LHS lacks a __mul__ method or if the method refuses its argument
(returns NotImplemented).

Likewise for other "reflected" methods.




More information about the Python-list mailing list