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.
Set your starting condition (see Python documentation):
net_force = sum(l, vector(0, 0))
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