为什么sum的行为与加号(+)操作不同

  • 本文关键字:操作 sum python sum
  • 更新时间 :
  • 英文 :


为什么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。

sumstart参数初始化为Item类型的对象,因为它的默认类型是int类型的对象,如docs:sum(iterable, /, start=0)中所述,其中0int

print(sum([Item(2), Item(4)], start=Item(0)).factor)

最新更新