In Python, is it possible for your class's __rmul__
method to override another class's __mul__
method, without making changes to the other class?
This question arises since I'm writing a class for a certain type of linear operator, and I want it to be able to multiply numpy arrays using the multiplication syntax. Here is a minimal example illustrating the issue:
import numpy as np class AbstractMatrix(object): def __init__(self): self.data = np.array([[1, 2],[3, 4]]) def __mul__(self, other): return np.dot(self.data, other) def __rmul__(self, other): return np.dot(other, self.data)
Left multiplication works fine:
In[11]: A = AbstractMatrix() In[12]: B = np.array([[4, 5],[6, 7]]) In[13]: A*B Out[13]: array([[16, 19], [36, 43]])
But right multiplication defaults to np.ndarray
's version, which splits the array up and performs multiplication element-by-element (this not what is desired):
In[14]: B*A Out[14]: array([[array([[ 4, 8], [12, 16]]), array([[ 5, 10], [15, 20]])], [array([[ 6, 12], [18, 24]]), array([[ 7, 14], [21, 28]])]], dtype=object)
In this situation, how can I make it call my own class's __rmul__
on the original (unsplit) array?
Answers addressing the specific case of numpy arrays are welcome but I am also interested in the general idea of overriding methods of another third party class that cannot be modified.