Summing Class Instances

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

Here is an excerpt 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 an error message:

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

I assume that since it sum()initially sets the result to 0 and then iterates through the list, but I can only determine if things are added to vector, and not vice versa.

+3
source share
3 answers

Set the initial condition (see Python documentation ):

net_force = sum(l, vector(0, 0))
+6
source

Another option is to slightly change __add__to a special case, 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)

That will allow you sumto work without specifying the initial conditions ....

+2

:

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

or maybe you can find your answer here .

0
source

All Articles