4

I'm trying to use the built-in function sum() on a list of objects and get object as a result.

Here's an extract of my code:

class vector:

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

    def __add__(self, other):
        return vector(self.x+other.x, self.y+other.y)

l = []
l.append(vector(3, 5))
l.append(vector(-2, 3))
l.append(vector(0,-4))

net_force = sum(l)

I get the error:

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

I guess that's because sum() initially sets the result to 0 and then iterates over the list, but I can only define adding things to vector, not the other way round.

Bach
  • 6,145
  • 7
  • 36
  • 61
  • 2
    http://stackoverflow.com/questions/1218710/pythons-sum-and-non-integer-values – Hoopdady Feb 21 '14 at 13:37
  • Why do you create a new `vector`-object in the `__add__()`-function? Why not `self.x += other.x; self.y+=orther.y`? – msvalkon Feb 21 '14 at 13:39
  • 5
    @msvalkon Because that would be completely wrong. You don't want `a = b + c` to modify `b`, you want it to create a new vector and name it `a`. You may be thinking of `__iadd__`. –  Feb 21 '14 at 13:40
  • ah yes, of course, sorry. – msvalkon Feb 21 '14 at 13:41

3 Answers3

6

Set your starting condition (see Python documentation):

net_force = sum(l, vector(0, 0))
Phylogenesis
  • 7,775
  • 19
  • 27
2

Your other option is to modify __add__ slightly to special-case this, i.e.

class vector(object):

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

    def __add__(self, other):
        if other == 0:
            return self
        else:
            return vector(self.x+other.x, self.y+other.y)

Which would enable sum to work without specifying initial conditions....

Corley Brigman
  • 11,633
  • 5
  • 33
  • 40
0

You could do this:

net_force = vector(0,0)
for i in l:
    net_force += i

or else maybe you can find your answer here.

Community
  • 1
  • 1
Sanjii
  • 1
  • 3