+ 1

Please clarify it better

*Please clarify it better (step 1/4 - Python OO/Magic Methods)* Considering the code below, why are x and y used in the __add__ magic method? Is it because class Vector2D exposes x and y to all its underlying methods despite they (x and y) are local to __init__? Please forgive my ignorance. I believe that should be a bit clearer as this is Python. 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)

21st Feb 2019, 2:04 AM
Pedro Carneiro Jr
Pedro Carneiro Jr - avatar
1 Answer
+ 4
I'm not totally sure what you are asking, but I'll give it a shot! The `__add__` method doesn't use `x` and `y`, rather it uses `self.x` and `self.y`, which were set in the `__init__` method. The `x` and `y` variables are not visible inside `__add__`. `self` is a special variable that refers to the current object, and you can set variables on it. That is not really related to magic methods though - a lot of variable setting happens in `__init__` because it is the first thing that happens after object creation, but you can do it from everywhere. class Foo: def __init__(self): self.x = 4 def not_init(self): self.y = 10 # totally works bar = Foo() # __init__ is called here bar.not_init() bar.z = 5 # totally works too print(bar.x + bar.y + bar.z) # 19 Hope this helps!
21st Feb 2019, 2:22 AM
Schindlabua
Schindlabua - avatar