User defined __mul__ method is not commutative User defined __mul__ method is not commutative python python

User defined __mul__ method is not commutative


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() '''