我有一个与我自己的__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: :'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).
SO内部,执行了添加的0 + Point(0,0,0)
,您的同类不支持。
要解决这个问题,请通过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__()