How work Magic Method ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How work Magic Method ?

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)

24th Feb 2019, 7:56 PM
Pragesh Yadav
1 Answer
+ 4
In your example code, you have the __add__ method for the Vector2D class set. Anything within that function will run only when the class is being added to something else, with in this case it returning a new instance of the Vector2D class, with the x value being the addition of both x values of the classes being added and the y value being the y values of the classes being added. In this case, you have the first variable being a new instance of the Vector2D class with the x value being 5 and the y value being 7, and the second variable being an instance where x = 3 and y = 9. Adding both first and second will result in a new instance of the Vector2D class being created and set in the result variable, where the new parameters are x = 8 (first.x = 5 and second.x = 3, so 5 + 3 = 8), and y = 16 (first.y = 7, second.y = 9, 7 + 9 = 16).
24th Feb 2019, 8:11 PM
Faisal
Faisal - avatar