User Defined __mul__ Method Is Not Commutative
I wrote a class to represent vectors in Python (as an exercise) and I'm having problems with extending the built-in operators. I defined a __mul__ method for the vector class. The
Solution 1:
If you want commutativity for different types you need to implement __rmul__()
. If implemented, it is called, like all __r*__()
special methods, if the operation would otherwise raise a TypeError
. Beware that the arguments are swapped:
classFoo(object):
def__mul_(self, other):
''' multiply self with other, e.g. Foo() * 7 '''def__rmul__(self, other):
''' multiply other with self, e.g. 7 * Foo() '''
Solution 2:
I believe you are looking for __rmul__
Post a Comment for "User Defined __mul__ Method Is Not Commutative"