I there a way to implement rmul so that it works in both directions? I'm using mul to multiply two vectors a and b of class R3 element by element. Later I want to be able to multiply each element by a number with an operator like 2*a and a*2.
class R3(object):
def __init__(self,an_array):
self.a = an_array # of length 3
self.s = 3
def __mul__(self,that):
tmp = [0]*self.s
for i in range(self.s):
tmp[i] = self.a[i]*that.a[i]
return self.__class__(tmp)
def __rmul__(self,that):
tmp = [0]*self.s
for i in range(self.s):
tmp[i] = self.a[i]*that
return self.__class__(tmp)
so this works fine for a * b, b * a, 2*a, but not a*2!
You can not implement
__rmul__for both sides, because__rmul__is, by definition, for right multiplication. When you want to change the behaviour ofx * yyou have to look at eitherx.__class__.__mul__ory.__class__.__rmul__.a * busesR3.__mul__(OK)b * aalso usesR3.__mul__(OK)2 * afirst usesint.__mul__, fails, then triesR3.__rmul__instead (OK)a * 2usesR3.__mul__, fails, usesint.__rmul__, fails again (NOT OK!)The way you have written it currently,
__mul__assumesthatargument is anR3instance, and__rmul__assumesthatargument is a scalar.You can not modify
int.__rmul__, to change the behaviour of the last case, because you can't patch those built-in types. However, you can modify yourR3.__mul__to change that behaviour.You've implemented
__mul__to handle onlyR3instances passed intothat. Fix it so it can handle scalars passed intothataswell.