为什么__radd__无效

Tim*_*Tim 5 python

您好

试图了解如何__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'
Run Code Online (Sandbox Code Playgroud)

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

Ada*_*erg 11

运营商的Python文档

"只有当左操作数不支持相应的操作且操作数属于不同类型时,才会调用这些函数."

另见脚注2

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


Kab*_*bie 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
Run Code Online (Sandbox Code Playgroud)