Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing class instances [duplicate]

Tags:

python

object

sum

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.

like image 716
Mikołaj Rozwadowski Avatar asked Feb 13 '23 17:02

Mikołaj Rozwadowski


1 Answers

Set your starting condition (see Python documentation):

net_force = sum(l, vector(0, 0))
like image 196
Phylogenesis Avatar answered Feb 17 '23 07:02

Phylogenesis