gpt4 book ai didi

python - 为什么 __radd__ 不工作

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

你好

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

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

最佳答案

Python docs for operators

“这些函数只有在左操作数不支持相应操作且操作数类型不同时才会调用。”

See also Footnote 2

由于操作数是同一类型,所以需要定义__add__

关于python - 为什么 __radd__ 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4298264/

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