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

Why does sum behaves differently to the plus (+) operation

为什么 sum 的行为不像加号运算符? 如何在 class 上使用求和?

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.reduce 和 operator.add 也可以,但需要大量输入

这是因为 sum returns 'start' 值(默认值:0)加上可迭代的数字

>>> help(sum)
Help on built-in function sum in module builtins:
    
sum(iterable, /, start=0)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers

所以这相当于 0 + Item(2) + ... 因此 TypeError!。您可以传递 Item(0) 作为默认值,而不是 0。

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

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