【发布时间】:2014-02-21 13:33:34
【问题描述】:
我正在尝试在对象列表上使用内置函数sum() 并获取对象。
这是我的代码摘录:
class vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return vector(self.x+other.x, self.y+other.y)
l = []
l.append(vector(3, 5))
l.append(vector(-2, 3))
l.append(vector(0,-4))
net_force = sum(l)
我得到错误:
TypeError: unsupported operand type(s) for +: 'int' and 'instance'
我猜这是因为 sum() 最初将结果设置为 0,然后遍历列表,但我只能定义向 vector 添加内容,而不是相反。
【问题讨论】:
-
为什么要在
__add__()-函数中新建vector-object?为什么不self.x += other.x; self.y+=orther.y? -
@msvalkon 因为那是完全错误的。您不希望
a = b + c修改b,而是希望它创建一个新向量并将其命名为a。你可能会想到__iadd__。 -
啊,是的,当然,对不起。