据我所知,要在对象上强制转换sum()
,它必须是iterable,并且必须是“addable”,即它必须实现方法__iter__
和__add__
。然而,当我为我的班级做这件事时(只是一个例子),这是行不通的。
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'
如果我实现的
Point
与__radd__
相同,那么当我尝试__add__
时会得到一个属性错误:AttributeError: 'int' object has no attribute 'x'
基于这些错误,我的
sum()
在某个地方被分离成Points
但我不确定在哪里。谢谢你的帮助。
最佳答案
这是因为sum
以默认值int
开始,当执行sum(points)
时,实际发生的情况是sum
首先尝试添加0 + Point(0, 0)
并因此产生错误。,
关于模块内置函数和的帮助:
和(iterable,start=0,/)
返回“start”值(默认值: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)))
关于python - 为自定义数据类型实现sum(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58916396/