2017-05-11 94 views
0


我有一个关于覆盖操作数的问题。我只是试图覆盖自定义类中的__add__(self, other)运算符,这样它的元素(一个numpy数组)就可以添加到另一个numpy数组中。为了使两个方向的求和成为可能,我同时声明了__add__以及__radd__运算符。一个小例子:python class sum with numpy array

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) 

奇怪的是,我得到两个不同的输出。第一个输出中,从some_function就像预期:

Out[1] 
array([[ 4., 1.], 
     [ 1., 4.]]) 

第二输出给了我一个奇怪的现象:

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) 

是否有人有一个想法,这是为什么?
谢谢,马库斯:-)

回答