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

Help me plz !! Magic Methods (dunders)

help me understand the logic of this code : 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 !! CODE: 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)

30th Aug 2017, 7:52 AM
hossein hayati
hossein hayati - avatar
2 Answers
+ 2
a lot of questions in one thread. 1. lines first = .., second = ... creates two separate objects of the class. see class as template orj pattern, and object like a real good produced using template. 2. when code contains + , interpreter calls method __add__(), so the function def __add__() creates the rule (to be correct override) for the operator +, which basically adds two objects of the same class. (note, in python everything is an object!!!!!!!) 3. what do you mean by regular method? every class has its own methods. 1+2 and "1"+" 2" seems similar, but + is used from the different classes and the method is different. again, in python everything is an object. 4. I guess it is answered above. self and other are representatives of the same class(created by the same template). and the method works assuming they are from the same class.
30th Aug 2017, 8:12 AM
yuri
+ 4
1. When we call Vector2D for the second time it doesn't change anything about the first time. And the program then stores both under different variables. 2. result = first + second... It bassicaly makes two results - result of x number in function and result of y number in function. So when we call print(result.x) it prints result of x and when we call print(result.y) it prints result of y. 3. It's easier that way, I think so.
30th Aug 2017, 8:15 AM
Tim Thuma
Tim Thuma - avatar