[英]Custom class with __add__ to add with NumPy array
我有一个自定义类实现 __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
我首先测试 __add__
r1 = Foo(numpy.arange(3)) + numpy.arange(3,6)
print('type results = %s' % type(r1))
print('result = {}'.format(r1))
它导致了预期的结果
>>> __add__
>>> type self = <class '__main__.Foo'>
>>> type other = <type 'numpy.ndarray'>
>>> type results = <type 'numpy.ndarray'>
>>> result = [3 5 7]
但是,测试 __radd__
r2 = numpy.arange(3) + Foo(numpy.arange(3,6))
print('type results = %s' % type(r2))
print('result = {}'.format(r2))
我得到
>>> __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])]
这对我来说没有任何意义。 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
由于 Python 操作符解析
N(3) + np.array([1, 2, 3])
将获得于上述__add__
与N(3)
和整个阵列作为other
一次,然后进行常规numpy的加成。
另一方面
np.array([1, 2, 3]) + N(3)
将成功进入 Numpy 的 ufuncs(在本例中为运算符),因为它们将任意对象作为“其他”,然后尝试依次执行:
1 + N(3)
2 + N(3)
3 + N(3)
这意味着上面的__add__
将被调用 3 次而不是一次,每个元素一次,显着减慢操作。 要禁用此行为,并使Numpy
在获取N
对象时引发NotImplementedError
从而允许 RHS 重载radd
接管,请将以下内容添加到类的主体中:
class N:
...
__numpy_ufunc__ = None # Numpy up to 13.0
__array_ufunc__ = None # Numpy 13.0 and above
如果向后兼容性不是问题,则只需要第二个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.