I have a question concerning overriding operands. I just tried to override the __add__(self, other)
operator in a custom class, such that on of its elements (a numpy array) can be added to another numpy array. To make both directions of summing possible I both declared the __add__
as well as the __radd__
operator. A small example:
我有一个关于重写操作数的问题。我只是试图覆盖自定义类中的__add __(self,other)运算符,这样就可以将其元素(一个numpy数组)添加到另一个numpy数组中。为了使两个求和方向成为可能,我都声明了__add__以及__radd__运算符。一个小例子:
import numpy as np
class MyClass():
def __init__(self, x):
self.x = x
self._mat = self._calc_mat()
def _calc_mat(self):
return np.eye(2)*self.x
def __add__(self, other):
return self._mat + other
def __radd__(self, other):
return self._mat + other
def some_function(x):
return x + np.ones(4).reshape((2,2))
def some_other_function(x):
return np.ones(4).reshape((2,2)) + x
inst = MyClass(3)
some_function(x=inst)
some_other_function(x=inst)
Strangely, I get two different outputs. The first ouput, from some_function
is just like expected:
奇怪的是,我得到两个不同的输出。来自some_function的第一个输出就像预期的那样:
Out[1]
array([[ 4., 1.],
[ 1., 4.]])
The second output gives me something odd:
第二个输出给了我一些奇怪的东西:
Out[2]:
array([[array([[ 4., 1.],
[ 1., 4.]]),
array([[ 4., 1.],
[ 1., 4.]])],
[array([[ 4., 1.],
[ 1., 4.]]),
array([[ 4., 1.],
[ 1., 4.]])]], dtype=object)
Does somebody have an idea why is that?
Thanks, Markus :-)
有人知道为什么会这样吗?谢谢,马库斯:-)
1 个解决方案
#1
2
the issue is that numpy array is also implementing an __add__
method, and it is called before your __radd__
问题是numpy数组也在实现__add__方法,并在__radd__之前调用它。
you can see this answer for a solution: https://*.com/a/22633052/7033869
你可以看到这个答案的解决方案:https://*.com/a/22633052/7033869
#1
2
the issue is that numpy array is also implementing an __add__
method, and it is called before your __radd__
问题是numpy数组也在实现__add__方法,并在__radd__之前调用它。
you can see this answer for a solution: https://*.com/a/22633052/7033869
你可以看到这个答案的解决方案:https://*.com/a/22633052/7033869