【发布时间】:2016-03-08 11:57:14
【问题描述】:
默认情况下,如果 numpy 不知道另一个对象的类型,它会跨数组分配操作。这在大多数情况下都很有效。例如,以下行为符合预期。
np.arange(5) + 5 # = [5, 6, 7, 8, 9]
我想定义一个覆盖加法运算符的类,如下面的代码所示。
class Example:
def __init__(self, value):
self.value = value
def __add__(self, other):
return other + self.value
def __radd__(self, other):
return other + self.value
它适用于标量值。例如,
np.arange(5) + Example(5) # = [5, 6, 7, 8, 9]
但是,它并不能完全满足我对向量值的要求。例如,
np.arange(5) + Example(np.arange(5))
产生输出
array([array([0, 1, 2, 3, 4]), array([1, 2, 3, 4, 5]),
array([2, 3, 4, 5, 6]), array([3, 4, 5, 6, 7]),
array([4, 5, 6, 7, 8])], dtype=object)
因为前面 numpy 数组的 __add__ 运算符优先于我定义的 __radd__ 运算符。 Numpy 的 __add__ 运算符为 numpy 数组的每个元素调用 __radd__,从而产生一个数组数组。如何避免 numpy 分发操作?我想避免子类化 numpy 数组。
【问题讨论】:
标签: python numpy operator-overloading