+ 3

Trouble understanding magic methods

#i don't understand the order of operations for this example. #in the add function, it looks like other.x value shouldn't be definded, and the self.y and other.y values aren't being used sometimes? #which variablesgo through the init? 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)

28th Sep 2017, 2:17 AM
Daniel Attner
Daniel Attner - avatar
3 odpowiedzi
+ 13
Not a Python expert, but __add__ means that you are overloading the "+" operator. That implies that both self and other are of class Vector2D, so they have x and y. As a result you should get 816 printed ( 5+3 7+9)
28th Sep 2017, 3:14 AM
Nikolay Nachev
Nikolay Nachev - avatar
+ 1
with result ur adding ro objects and that is wrong and u defined a method but did not use it
28th Sep 2017, 5:36 AM
jay
+ 1
Def __init__ initialises the object. The __add__ defines ehat happens when you add 2 such objects. Thus, when the code is run it executes tgis way
28th Sep 2017, 11:42 PM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar