I have a class with my own implementation of __add__:
class Point(namedtuple('Point', ['x', 'y', 'z'])):
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y, self.z + other.z)
Addition works as expected:
l = [Point(0,0,0), Point(0,1,2)]
s = l[0]
for a in l[1:]:
s = s + a
But when I use builtin sum I'm getting an error:
s = sum(l)
TypeError: unsupported operand type(s) for +: 'int' and 'Point'
What's wrong in my code? Doesn't sum use __add__? What more should I override?
The sum function initializes its result variable with the integer value 0:
sum(iterable[, start]) -> value
Return the sum of an iterable of numbers (NOT strings) plus the value
of parameter 'start' (which defaults to 0).
So inside of sum, the addition 0 + Point(0,0,0) is performed, which your class doesn't support.
To get around this, pass a suitable value for start:
s = sum(l, Point(0,0,0))
You could also override the __radd__() function:
def __radd__(self, other):
return Point(self.x + other, self.y + other, self.z + other)
Note that this must be done additionally to overriding __add__()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With