说我有一个清单l.在什么情况下被l.__rmul__(self, other)称为?
我基本上理解了文档,但我也希望看到一个例子,毫无疑问地澄清它的用法.
这个问题与Overriding other __rmul__ with your class's __mul__中提出的问题很接近,但我的印象是,这是一个比数值数据更普遍的问题。另外,这个问题没有得到解答,我真的不想使用矩阵乘法@来进行此操作。因此,问题。
我确实有一个接受标量和数值数组相乘的对象。与往常一样,左乘法工作得很好,因为它myobj()使用的是方法,但在右乘法中,NumPy 使用广播规则并给出元素级结果dtype=object。
这还有一个副作用,即无法检查数组的大小是否兼容。
因此,问题是
有没有办法强制 numpy 数组查找
__rmul__()另一个对象的 ,而不是广播和按元素执行__mul__()?
在我的特定情况下,对象是 MIMO(多输入、多输出)传递函数矩阵(或者滤波器系数矩阵,如果您愿意),因此矩阵乘法在线性系统的加法和乘法方面具有特殊含义。因此在每个条目中都有SISO系统。
import numpy as np
class myobj():
def __init__(self):
pass
def __mul__(self, other):
if isinstance(other, type(np.array([0.]))):
if other.size == 1:
print('Scalar multiplication')
else:
print('Multiplication of arrays')
def __rmul__(self, other):
if isinstance(other, type(np.array([0.]))):
if other.size == 1:
print('Scalar multiplication')
else:
print('Multiplication of arrays')
A = myobj()
a = np.array([[[1+1j]]]) # some generic scalar
B …Run Code Online (Sandbox Code Playgroud)