gpt4 book ai didi

python - 如何调用 __add__

转载 作者:行者123 更新时间:2023-11-28 21:22:23 27 4
gpt4 key购买 nike

class C(object):
def __init__(self, value):
self.value = value

def __add__(self, other):
if isinstance(other, C):
return self.value + other.value
if isinstance(other, Number):
return self.value + other
raise Exception("error")


c = C(123)

print c + c

print c + 2

print 2 + c

显然,前两个 print 语句可以工作,第三个失败,因为 int.add() 无法处理 C 类实例。

246
125
print 2 + c
TypeError: unsupported operand type(s) for +: 'int' and 'C'

有没有办法解决这个问题,所以 2+c 会导致 C.add() 被调用?

最佳答案

您需要添加 __radd__以及处理相反的情况:

def __radd__(self, other):
if isinstance(other, C):
return other.value + self.value
if isinstance(other, Number):
return other + self.value
return NotImplemented

并注意你不应该抛出异常;而是返回 NotImplemented 单例。这样,other 对象仍然可以尝试为您的对象支持 __add____radd__,并且也有机会实现加法。

当您尝试添加两种类型ab 时,Python 首先尝试调用a.__add__(b);如果该调用返回 NotImplemented,则会尝试 b.__radd__(a)

演示:

>>> from numbers import Number
>>> class C(object):
... def __init__(self, value):
... self.value = value
... def __add__(self, other):
... print '__add__ called'
... if isinstance(other, C):
... return self.value + other.value
... if isinstance(other, Number):
... return self.value + other
... return NotImplemented
... def __radd__(self, other):
... print '__radd__ called'
... if isinstance(other, C):
... return other.value + self.value
... if isinstance(other, Number):
... return other + self.value
... return NotImplemented
...
>>> c = C(123)
>>> c + c
__add__ called
246
>>> c + 2
__add__ called
125
>>> 2 .__add__(c)
NotImplemented
>>> 2 + c
__radd__ called
125

关于python - 如何调用 __add__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19294677/

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