[Tutor] operators

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Thu Mar 27 12:47:02 2003


On Thu, 27 Mar 2003, Aurelio Magalhaes Dias wrote:

> > Im wondering if anyone can tell me how to define an operator to work
> > on multiple types.  In my case Im trying to construct a class for
> > matricies and I would like to define matrix multiplication to either
> > multiply 2 matricies or to multiply a matrix by a scalar depending on
> > what is given in the argument.

Hi Issac,

Would it be ok to make two separate methods, one to do scalar
multiplication, and one to do matrix multiplication?


It sounds like you want to do the "polymorphism" that languages like C++
and Java support.  Python doesn't automatically support "polymorphic"
functions, but we can simulate it by doing a runtime check on the
arguments to __mul__.  For example:

###
>>> class MulTest:
...     def __mul__(self, other):
...         if isinstance(other, MulTest):
...             return MulTest()
...         else:
...             return other
...
>>> x = MulTest()
>>> y = MulTest()
>>> z = "mulberry"
>>> x*y
<__main__.MulTest instance at 0x810f0a4>
>>> x*z
'mulberry'
>>> y*z
'mulberry'
###

Here, we make a decision based on what isinstance()  tells us about the
'other' argument.  In your matrix code, you can check to see if the
argument is a "scalar" or another matrix, and then branch from there.


Note that doing 'z*x' isn't automatically supported!

###
>>> z*x
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for *: 'str' and 'instance'
###

But we can fix that.  To make it work, we need to also define an
__rmul__() method that tells Python what to do when our instance is on the
right hand side of the multiplication.



See:

    http://python.org/doc/current/ref/numeric-types.html

for more details on writing overloaded operators.


I hope this helps!