Reputation: 461
It feels like such a simple thing but I can't seem to find the info I need. Say I define a class Matrix:
class Matrix():
def __mul__(self, other):
if isinstance(other, Matrix):
#Matrix multiplication.
if isinstance(other, int): #or float, or whatever
#Matrix multiplied cell by cell.
This work fine if I multiply a matrix by an int, but since int doesn't know how to deal with matrices, 3*Matrix raises a TypeError. How do I deal with this?
Upvotes: 3
Views: 123
Reputation: 24788
Define __rmul__
to override the calling of int()
's __mul__
method:
class Matrix():
# code
def __rmul__(self, other):
#define right multiplication here.
#As Ignacio said, this is the ideal
#place to define matrix-matrix multiplication as __rmul__() will
#override __mul__().
# code
Note that you can do this with all of the numeric operators.
Also note that it's better to use new style classes, so define your class as:
class Matrix(object):
This will allow you to do things like:
if type(other) == Matrix: ...
Upvotes: 4