In a project, I created a class, and I needed an operation between this new class and a real matrix, so I overloaded the __rmul__
function like this
class foo(object):
aarg = 0
def __init__(self):
self.aarg = 1
def __rmul__(self,A):
print(A)
return 0
def __mul__(self,A):
print(A)
return 0
but when I called it, the result wasn't what I expected
A = [[i*j for i in np.arange(2) ] for j in np.arange(3)]
A = np.array(A)
R = foo()
C = A * R
Output:
0
0
0
1
0
2
It seems that the function is called 6 times, once for each elements.
Instead, the __mul__
function works greatly
C = R * A
Output:
[[0 0]
[0 1]
[0 2]]
If A
isn't an array, but only a list of lists, both work fine
A = [[i*j for i in np.arange(2) ] for j in np.arange(3)]
R = foo()
C = A * R
C = R * A
Output
[[0, 0], [0, 1], [0, 2]]
[[0, 0], [0, 1], [0, 2]]
I'd really want for my __rmul__
function to work also on arrays (my original multiplication function isn't commutative). How can I solve it?