为什么sum的行为不像加号操作符?我怎样在课堂上使用sum ?
class Item:
def __init__(self, factor):
self.factor = factor
def __add__(self, other):
return Item(self.factor + other.factor)
print((Item(2) + Item(4)).factor) # 6
print(sum([Item(2), Item(4)]).factor) # TypeError: unsupported operand type(s) for +: 'int' and 'Item'
出现itertools。用运算符进行约简。Add也可以,但是要输入很多
这是因为sum
返回'start'值(默认为0)加上一个可迭代的数字
>>>帮助(总和)关于模块内置函数sum的帮助:Sum (iterable,/,start=0)返回'start'值的和(默认值:0)加上数字
的可迭代对象,因此这相当于0 + Item(2) + ...
,因此TypeError
!您可以传递Item(0)
作为默认值,而不是0。
将sum
的start
参数初始化为Item
类型的对象,因为它的默认类型是int
类型的对象,如docs:sum(iterable, /, start=0)
中所述,其中0
是int
。
print(sum([Item(2), Item(4)], start=Item(0)).factor)