how does this code work..? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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)

9th Mar 2017, 10:02 AM
ANAS
ANAS - avatar
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.
9th Mar 2017, 4:18 PM
Álvaro