[Numpy-discussion] What's the difference between calling __mul__ and *?

Toder, Evgeny evgeny.toder at jpmorgan.com
Fri Jun 7 12:38:22 EDT 2013

That's how it works in python:

Note: If the right operand's type is a subclass of the left operand's type and that subclass provides the reflected method for the operation, this method will be called before the left operand's non-reflected method. This behavior allows subclasses to override their ancestors' operations.

Note that matrix is a subclass of ndarray.
Also note that __mul__ can return NotImplemented, in which case again the method of rhs argument will be used.


-----Original Message-----
From: numpy-discussion-bounces at scipy.org [mailto:numpy-discussion-bounces at scipy.org] On Behalf Of Will Lee
Sent: Friday, June 07, 2013 12:30 PM
To: Discussion of Numerical Python
Subject: [Numpy-discussion] What's the difference between calling __mul__ and *?

Can somebody tell me why these operations are not the same in numpy?

In [2]: a = numpy.array([1, 2, 3.])

In [4]: matrix = numpy.matrix([[1, 2, 3.], [4, 5, 6], [7, 8, 9]])

In [5]: a.__mul__(matrix)

matrix([[  1.,   4.,   9.],

        [  4.,  10.,  18.],

        [  7.,  16.,  27.]])

In [6]: a * matrix

matrix([[ 30.,  36.,  42.]])

Essentially I'm trying to extend from numpy.ndarray.  From my subclass
__mul__ I'd like to call the parent's __mul__ method.  I ran into
problem when I'm trying to call super(SubArrayClass, self).__mul__()
method when working with a matrix.  I also can't think of a way to use
operator.mul() due to the subclass nature.  Is there any way to make
this work?

Any help is greatly appreciated.


NumPy-Discussion mailing list
NumPy-Discussion at scipy.org
This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  

More information about the NumPy-Discussion mailing list