Is 8 getting passed to first here . Plz say and 16 to second and also is result storing them.
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)
OBJECT [PROPERTY] first [ x:5 y:7 ] second. [ x:3 y:9 ] --------------------------------- + result [ x:8 y:16 ] This is how the magic method does its work, create 'result' and assign it x property with sum of first.x + second.x, and y property with sum of first y + second.y adarsh pandey
adarsh pandey understand that the Vector2D class here implements the __add__ magic method which returns a new instance of Vector2D where the new object's x property equals its own x property + other x property, and new object's y property equals its own y property + other y property. First, you see an object is created (named first) based on class Vector2D, the object is initialized with property x=5, and y=7. Second, another object is created (named second) based on class Vector2D which is initialized with property x=3 and y=9. Third, another object is created (named result), but note here, we didn't create the object as usual, instead we use the magic method implementation __add__, so when we do 'result = first + second' a new object is returned with x property equals [ first.x (5) + second.x (3) ] = 8. And the y property equals [ first y (7) + second.y (9) ] = 16. Then the result object is a new instance of Vector2D with x=8, and y=16. Hth, cmiiw
According to Code Playground, result's x is 8 and y is 16, so all your questions answer is "Yes".
but how is it returning the value of 8 to first and 16 to second and why are we saying result. x and result. y ? in which type did we do that? list, tuples or dictionaries????