I have a simple vector class that overloards several arithmetic operators:
class vec2:
x = 0.0
y = 0.0
def __add__(self,other):
self.x = other.x
self.y = other.y
def __mul__(self,scalar):
self.x *= scalar
self.y *= scalar
However, somewhere else I call the method like this:
class foo:
position = vec2()
velocity = vec2()
def update(self,dt):
self.position += self.velocity * dt;
However, once I get to the update function, the interpreter gives an error:
'tuple' object has no attribute 'x'
inside the __add__ function.
Why is “other” in __add__ passed as a tuple, and not a vec2?
The entire code is here.
Return new vectors when using
__add__and__mul__, and handle ‘strange’ types:To modify the vectors in-place, use
__iadd__and__imul__; these still need to return the new value; this can beself.Note that this does not handle just passing in a tuple of
(x, y)coordinates. If you want to support that usecase, you need to specially handle it:Note also that you should not really use class attributes for your position and velocity values; I’ve used instance attributes instead above, and took the opportunity to set both position and velocity to sane values.
Demo: