Help !! Magic Methods (dunders) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Help !! Magic Methods (dunders)

help me understand the logic of this code : ( I mean what is happening in the program ) 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)

29th Aug 2017, 8:06 AM
hossein hayati
hossein hayati - avatar
3 Answers
+ 2
Magic methods allow you to define how operators like + work for your classes. In this case, the program defines a class named Vector2D, a method for initializing it (__init__), and a method for adding one Vector2D with another (__add__). Then it creates two instances of the class and adds them together to show you how it works.
29th Aug 2017, 8:21 AM
Adam Blažek
Adam Blažek - avatar
+ 2
my problem is that: 1. when we call Vector2D for the second time, what will happen to the first one ?? does the program store it somewhere ??? and 2. where we defined that + in this line result = first + second would give us the sum of the elements ?? 3.why we cannot do it with the regular methods ?? 4.why in this line def __add__(self, other): other is operating just like self but in __init__ the other values will use as unknowns !!
30th Aug 2017, 7:50 AM
hossein hayati
hossein hayati - avatar
+ 1
Simply, writing a + b is exactly the same as a.__add__(b) or, if not defined, b.__radd__(a)
30th Aug 2017, 9:38 AM
Adam Blažek
Adam Blažek - avatar