2010-11-28 105 views
5

HI爲什麼__radd__不能正常工作

試圖瞭解__radd__是如何工作的。我有密碼

>>> class X(object): 
    def __init__(self, x): 
     self.x = x 
    def __radd__(self, other): 
     return X(self.x + other.x) 


>>> a = X(5) 
>>> b = X(10) 
>>> a + b 

Traceback (most recent call last): 
    File "<pyshell#8>", line 1, in <module> 
    a + b 
TypeError: unsupported operand type(s) for +: 'X' and 'X' 
>>> b + a 

Traceback (most recent call last): 
    File "<pyshell#9>", line 1, in <module> 
    b + a 
TypeError: unsupported operand type(s) for +: 'X' and 'X' 

爲什麼這不起作用?我在這裏做錯了什麼?

+0

只是想看看__radd__作品。我知道我可以使用__add__ – Tim 2010-11-28 18:31:42

回答

6

這些函數僅在左操作數不支持相應操作且操作數類型不同的情況下才會調用。

我使用Python3所以請忽略語法差異:

>>> class X: 
    def __init__(self,v): 
     self.v=v 
    def __radd__(self,other): 
     return X(self.v+other.v) 
>>> class Y: 
    def __init__(self,v): 
    self.v=v 

>>> x=X(2) 
>>> y=Y(3) 
>>> x+y 
Traceback (most recent call last): 
    File "<pyshell#120>", line 1, in <module> 
    x+y 
TypeError: unsupported operand type(s) for +: 'X' and 'Y' 
>>> y+x 
<__main__.X object at 0x020AD3B0> 
>>> z=y+x 
>>> z.v 
5 
-1

嘗試此

類X(對象):

def __init__(self, x): 

    self.x = x 

def __radd__(self, other): 

    return self.x + other 

一個= X(5)

b = X(10)

打印總和([A,B])

0

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

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'