TypeError: unsupported operand type(s) for + when using sum
TypeError: unsupported operand type(s) for + when using sum
我有一个 class 我自己实现了 __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)
,您的 class 不支持。
要解决这个问题,请为 start
:
传递一个合适的值
s = sum(l, Point(0,0,0))
您还可以覆盖 __radd__()
函数:
def __radd__(self, other):
return Point(self.x + other, self.y + other, self.z + other)
请注意,除了覆盖 __add__()
之外 还必须完成此操作
我有一个 class 我自己实现了 __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)
,您的 class 不支持。
要解决这个问题,请为 start
:
s = sum(l, Point(0,0,0))
您还可以覆盖 __radd__()
函数:
def __radd__(self, other):
return Point(self.x + other, self.y + other, self.z + other)
请注意,除了覆盖 __add__()