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 * y
you have to look at eitherx.__class__.__mul__
ory.__class__.__rmul__
.a * b
usesR3.__mul__
(OK)b * a
also usesR3.__mul__
(OK)2 * a
first usesint.__mul__
, fails, then triesR3.__rmul__
instead (OK)a * 2
usesR3.__mul__
, fails, usesint.__rmul__
, fails again (NOT OK!)The way you have written it currently,
__mul__
assumesthat
argument is anR3
instance, and__rmul__
assumesthat
argument 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 onlyR3
instances passed intothat
. Fix it so it can handle scalars passed intothat
aswell.