为什么__radd__不起作用

时间:2010-11-28 18:26:54

标签: python

HI

试图了解__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'

为什么这不起作用?我在这里做错了什么?

4 个答案:

答案 0 :(得分:11)

Python docs for operators

“仅当左操作数不支持相应操作且操作数类型不同时才调用这些函数。”

See also Footnote 2

由于操作数的类型相同,因此您需要定义__add__

答案 1 :(得分: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

答案 2 :(得分: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'

答案 3 :(得分:-1)

试试这个

class X(object):

 def __init__(self, x):

     self.x = x

 def __radd__(self, other):

     return self.x + other

a = X(5)

b = X(10)

打印总和([a,b])