+ 2
how does this code work..?
class Vector2D: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Vector2D(self.x + other.x, self.y + other.y) first = Vector2D(5, 7) second = Vector2D(3, 9) result = first + second print(result.x) print(result.y)
1 Answer
+ 2
An object (say, for example, "obj") of class Vector2D has 2 components, namely obj.x and obj.y âthat's how you defined the __init__ method. When you add 2 Vector2D objects, using "+", then the __add__ method is automatically called.