Search code examples
pythonsum

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


How come sum does not behave like the plus operator? How can I use sum on my 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 with operator.add also works but it's a lot of typing


Solution

  • Initialize the start argument of sum to an object of type Item as its default is an object of type int as in stated in the docs: sum(iterable, /, start=0) where 0 is an int.

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