Python 中加法表达式的顺序重要吗?

Does the order of addition expressions matter in Python?

这听起来有点愚蠢,但我不是在谈论 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
>>>

我不明白为什么第一个 returns 出错而第二个正常

是的,顺序很重要。

第一种情况,调用了int__add__方法(它当然不知道如何给自己添加一个非数字class的实例) ;在第二种情况下,调用了 num__add__ 方法。

如果 __add__ 方法失败,那么 Python 可以检查替代方法,正如 user2357112 指出的那样。

不假定加法是可交换的 - 例如,[1] + [2] != [2] + [1] - 所以当你的对象位于 + 的右侧时,你需要实现一个单独的方法左边不知道怎么处理

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

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