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?