0

I have a class with a custom __add__ method.

class Example:
    def __init__(x, y):
        self.x = x
        self.y = y

    def __add__(self, example):
        return Example(
          x=self.x + example.x,
          y=self.y + example.y
               )

Now let's say I create two objects and add them.

example_1, example_2 = Example(4, 5), Example(2, 3)
example_summed = example_1 + example_2
print(example_summed.x)

# Outputs:

-> 6

Okay, works as expected. However in practise I have to sum a large, variable number of objects. So I want to sum them with sum function. When I do:

example_summed = sum([example_1, example_2])

I get the error:

TypeError: unsupported operand type(s) for +: 'int' and 'Example'

It's almost as if the sum function is trying to add an int into the sum. Presumably, if I'm right, it's adding a zero (addition identity operator).

So, why is this failing? Is there a hidden zero?

4
  • 9
    sum uses a start parameter, which is 0 by default. Commented Oct 14, 2021 at 12:50
  • Python doesn't have a concept of monoids. You have to supply the proper identity yourself to sum, rather than having some way of defining it in the type along with __add__. Commented Oct 14, 2021 at 13:10
  • sum(xs, start=s) == s + xs[0] + xs[1] + ... + xs[-1]. It always uses the start value, rather than only using it if there are fewer than 2 values in the sequence to sum. Commented Oct 14, 2021 at 13:12
  • If it makes sense at all to treat x the same as Example(x, x), it might be worth doing so in your definition of Example.__add__. Commented Oct 14, 2021 at 13:15

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.