sygi
sygi

Reputation: 4637

TypeError: unsupported operand type(s) for + when using sum

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?

Upvotes: 3

Views: 4469

Answers (2)

rammelmueller
rammelmueller

Reputation: 1118

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__()

Upvotes: 2

Aran-Fey
Aran-Fey

Reputation: 43146

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))

Upvotes: 4

Related Questions