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__
meth
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:
class Foo(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() '''
I believe you are looking for __rmul__