gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:50:59 25 4
gpt4 key购买 nike

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

我不明白为什么第一个返回错误而第二个正常工作

最佳答案

不假定加法是可交换的 - 例如,[1] + [2] != [2] + [1] - 所以当你的object 在 + 的右边,而左边的东西不知道如何处理它。

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

所有其他二元运算都存在类似的方法,所有这些都是通过在同一位置粘贴 r 来命名的。

关于python - 加法表达式的顺序在 Python 中重要吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29665382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com