2012-02-03 57 views
3
class exampleclass1: 
    def __init__(self, data): 
     self.data = data 

    def __add__(self, other): 
     if isinstance(other, int): 
      print('blabla') 


class exampleclass2: 
    def __init__(self, data): 
     self.data = data 

    def __add__(self, other): 
     if isinstance(other, exampleclass1): 
      print("it's working yay") 

    __radd__ = __add__ 

a = exampleclass1('q') 

b = exampleclass2('w') 

a+b 

我的問題是這樣的:我有兩個不同的類,我想定義它們只在一個類中的添加,併爲該類定義add和radd(在本例中這是exampleclass2。我不想創建一個add方法,可用於exampleclass1添加exampleclass2使用radd方法之間的類之間的加法

因爲它是現在它只是忽略它,我也嘗試提出錯誤,但也沒有工作。高興得到我的幫助!:)

回答

10

__radd__僅在左對象沒有__add__方法od,或者該方法不知道如何添加兩個對象(它通過返回NotImplemented來標記)。兩個類都有一個__add__方法,它不返回NotImplemented。因此__radd__方法永遠不會被調用。

+0

啊,NotImplemented,這正是我一直在尋找的功能。尼斯 – user1187139 2012-02-04 02:36:31

2

這些功能__radd__如果左操作數不 不支持相應的操作只被調用和操作數是 不同的類型。例如,

class X: 
    def __init__(self, num): 
    self.num = num 

class Y: 
    def __init__(self, num): 
    self.num = num 

    def __radd__(self, other_obj): 
    return Y(self.num+other_obj.num) 

    def __str__(self): 
    return str(self.num) 

>>> x = X(2) 
>>> y = Y(3) 
>>> print(x+y) 
5 
>>> 
>>> print(y+x) 
--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-60-9d7469decd6e> in <module>() 
----> 1 print(y+x) 

TypeError: unsupported operand type(s) for +: 'Y' and 'X'