2017-05-11 152 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) 

是否有人有一個想法,這是爲什麼?
謝謝,馬庫斯:-)

回答