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?
Define
__rmul__to override the calling ofint()‘s__mul__method: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:
This will allow you to do things like: