overloading __mul__

Michael Amrhein michael.amrhein at t-online.de
Wed Mar 12 08:11:07 EST 2003


zunbeltz schrieb:
> Hello
> 
> I'm defining 2 clases. They are like a matrix anda a vector.  The
> matrix
> is a square one using list insie list [[1,2],[3,4]] and the vector is
> a list [5,6].
> 
> I want to be able to write things like that 
>   2*matrix 
>   matrix * 2
>   2*vector
>   vector *2
> but also
>   matrix*vector
>   vector*matrix
> 
> How can i overload __mul__ for matrix in two ways depending if the
> other elemetn is a number or a vecotr? and in wich class have i to
> overload __mul__ to get vector * matrix and matrix * vector; in the
> vector class? in the matrix class? in both?
> 
> thanks in advance
> 
> Zunbeltz
class matrix(object):
   ...
   # self * other
   def __mul__(self, other):
     if isinstance(other, matrix):
       ...
     elif isinstance(other, vector):
       ...
     else:
       ...
   # other * self
   __rmul__ = __mul__
   ...
Simular for vector.

Michael





More information about the Python-list mailing list