Max*_*Max 7 python numpy operator-overloading
我有一个自定义类实现 __add__ 和 __radd__ 作为
import numpy
class Foo(object):
def __init__(self, val):
self.val = val
def __add__(self, other):
print('__add__')
print('type self = %s' % type(self))
print('type other = %s' % type(other))
return self.val + other
def __radd__(self, other):
print('__radd__')
print('type self = %s' % type(self))
print('type other = %s' % type(other))
return other + self.val
Run Code Online (Sandbox Code Playgroud)
我首先测试 __add__
r1 = Foo(numpy.arange(3)) + numpy.arange(3,6)
print('type results = %s' % type(r1))
print('result = {}'.format(r1))
Run Code Online (Sandbox Code Playgroud)
它导致了预期的结果
>>> __add__
>>> type self = <class '__main__.Foo'>
>>> type other = <type 'numpy.ndarray'>
>>> type results = <type 'numpy.ndarray'>
>>> result = [3 5 7]
Run Code Online (Sandbox Code Playgroud)
但是,测试 __radd__
r2 = numpy.arange(3) + Foo(numpy.arange(3,6))
print('type results = %s' % type(r2))
print('result = {}'.format(r2))
Run Code Online (Sandbox Code Playgroud)
我得到
>>> __radd__
>>> type self = <class '__main__.Foo'>
>>> type other = <type 'int'>
>>> __radd__
>>> type self = <class '__main__.Foo'>
>>> type other = <type 'int'>
>>> __radd__
>>> type self = <class '__main__.Foo'>
>>> type other = <type 'int'>
>>> type results = <type 'numpy.ndarray'>
>>> result = [array([3, 4, 5]) array([4, 5, 6]) array([5, 6, 7])]
Run Code Online (Sandbox Code Playgroud)
这对我来说没有任何意义。NumPy 是否为任意对象重载 __add__,然后优先于我的 __radd__?如果是,他们为什么要这样做?此外,我该如何避免这种情况,我真的希望能够在左侧添加带有 NumPy 数组的自定义类。谢谢。
这被评论隐藏了,但应该是答案。
默认情况下,Numpy 操作在每个元素的基础上进行,获取任意对象,然后尝试按元素执行操作(根据广播规则)。
例如,这意味着给定
class N:
def __init__(self, x):
self.x = x
def __add__(self, other):
return self.x + other
def __radd__(self, other):
return other + self.x
Run Code Online (Sandbox Code Playgroud)
由于Python的运算符解析
N(3) + np.array([1, 2, 3])
Run Code Online (Sandbox Code Playgroud)
将得到上面的__add__
和N(3)
整个数组other
一次,然后执行常规的 Numpy 加法。
另一方面
np.array([1, 2, 3]) + N(3)
Run Code Online (Sandbox Code Playgroud)
将成功进入 Numpy 的 ufunc(在本例中为运算符),因为它们将任意对象作为“其他”,然后尝试连续执行:
1 + N(3)
2 + N(3)
3 + N(3)
Run Code Online (Sandbox Code Playgroud)
这意味着__add__
上面将被调用 3 次,而不是一次,每个元素调用一次,从而显着减慢操作速度。要禁用此行为,并在获取对象时Numpy
提出 a ,从而允许 RHS 过载NotImplementedError
N
radd
,请将以下内容添加到类的主体中:
class N:
...
__numpy_ufunc__ = None # Numpy up to 13.0
__array_ufunc__ = None # Numpy 13.0 and above
Run Code Online (Sandbox Code Playgroud)
如果向后兼容性不是问题,则只需要第二个。