+ 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)
3 Antworten
+ 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.
+ 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 !!
+ 1
Simply, writing
a + b
is exactly the same as
a.__add__(b)
or, if not defined,
b.__radd__(a)