添加表达式的顺序在Python中是否重要?

jkd*_*jkd 4 python methods

这听起来有点愚蠢,但我不是在谈论1 + 2 = 2 + 1.我在谈论带有__add__方法的对象添加到数字的位置.一个例子是:

>>> class num:
...     def __add__(self,x):
...             return 1+x
... 
>>> n = num()
>>> 1+n
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'instance'
>>> n+1
2
>>>
Run Code Online (Sandbox Code Playgroud)

我不明白为什么第一个返回错误而第二个像普通一样工作

use*_*ica 8

不假设加法是可交换的 - 例如,[1] + [2] != [2] + [1]- 当你的对象位于a的右侧+并且左边的东西不知道如何处理它时,你需要实现一个单独的方法.

def __radd__(self, other):
    # Called for other + self when other can't handle it or self's
    # type subclasses other's type.
Run Code Online (Sandbox Code Playgroud)

对于所有其他二进制操作存在类似的方法,所有这些操作都通过r在同一位置粘贴来命名.