gpt4 book ai didi

python - 类型错误 : unsupported operand type(s) for + when using sum

转载 作者:太空宇宙 更新时间:2023-11-03 13:32:41 25 4
gpt4 key购买 nike

我有一个包含我自己的 __add__ 实现的类:

class Point(namedtuple('Point', ['x', 'y', 'z'])):
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y, self.z + other.z)

加法按预期工作:

l = [Point(0,0,0), Point(0,1,2)]
s = l[0]
for a in l[1:]:
s = s + a

但是当我使用内置的 sum 时出现错误:

s = sum(l)

TypeError: unsupported operand type(s) for +: 'int' and 'Point'

我的代码有什么问题? sum 不使用 __add__ 吗?我还应该覆盖什么?

最佳答案

sum 函数用整数值 0 初始化它的结果变量:

sum(iterable[, start]) -> value

Return the sum of an iterable of numbers (NOT strings) plus the value
of parameter 'start' (which defaults to 0).

因此在 sum 内部,执行加法 0 + Point(0,0,0),您的类不支持。

要解决这个问题,请为 start 传递一个合适的值:

s = sum(l, Point(0,0,0))

关于python - 类型错误 : unsupported operand type(s) for + when using sum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44331624/

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