据我所知,要想在对象上强制转换sum()
,它必须是可迭代的,并且必须是"可添加的",即它必须实现方法__iter__
和__add__
。然而,当我为我的类Point
(只是一个例子(这样做时,这是不起作用的。
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __iter__(self):
return self
def __str__(self):
return str((self.x, self.y))
print(Point(2, 2) + Point(1, 1))
>>> (3, 3) # As expected; good!
points = [Point(0, 0), Point(2, 0), Point(0, 2), Point(2, 2)]
print(sum(points)) # Expect (4, 4)
>>> TypeError: unsupported operand type(s) for +: 'int' and 'Point'
如果我实现与__add__
相同的__radd__
,那么当我尝试sum()
:时会得到一个属性错误
AttributeError: 'int' object has no attribute 'x'
根据这些错误,我的Points
在某个地方被分离为ints
,但我不确定在哪里。谢谢你的帮助。
之所以会发生这种情况,是因为sum
以默认值int
开始,而在执行sum(points)
时,实际发生的是sum
首先尝试添加0 + Point(0, 0)
,从而导致错误。如果你查看sum
上的帮助,这将变得非常明显,
模块内置函数和的帮助:
sum(可迭代,start=0,/(返回"开始"值(默认值:0(加上数字的可迭代值之和
When the iterable is empty, return the start value. This function is intended specifically for use with numeric values and may reject non-numeric types.
从更改行
>>> print(sum(points))
至
>>> print(sum(points, Point(0, 0)))