+ 1

Can anyone explain me what's going on in this piece of code ? 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) first = Vector2D(5, 7) second = Vector2D(3, 9) result = first + second print(result.x) print(result.y)

15th Jul 2018, 9:02 AM
adarsh pandey
adarsh pandey - avatar
7 Answers
+ 2
hey adarsh pandey here '+' operator is overloaded to add two objects of type Vector2D this is called polymorphism.
15th Jul 2018, 9:09 AM
Nikhil Dhama
Nikhil Dhama - avatar
+ 2
def __add__(self, other): return Vector2D(self.x + other.x, self.y + other.y) this is the definition self refers the class on which you are applying the method, other is the passing argument.( as + is a binary operator requires 2 operands) fisrt + second is equivalent to first.__add__(second)
15th Jul 2018, 9:17 AM
Nikhil Dhama
Nikhil Dhama - avatar
+ 1
the result variable add the values of first and second object. when you are add two objects then you need to define a function with magic method for add magic method is __add__ now, in magic method self is for first object and other is for second object. self.x=5 and self.y=3 other.x=3 and other.y=9 when __add__ method run it return tuple value. which is, self.x+other.x=8 and self.y+other.y=16 tuple is (8,16) first value of tuple is result.x and 2nd is result.y so output is 8 16
15th Jul 2018, 9:30 AM
Maninder $ingh
Maninder $ingh - avatar
+ 1
The first parameter after the __init__ magic method is represented as the variable name assigned to the call with class name as function. (first and second). When + is used for self class objects, the function with __add__ magic method is executed with the 2 self objects as the parameters, self first as self and self second as other. Then the function returns self.x + other.x and self.y + other.y as function parameters with class name as function to the variable result. first = Vector2D(5, 7) first.x = 5 first.y = 7 second = Vector2D(3, 9) second.x = 3 second.y = 9 result = first + second result = Vector2D(first.x + second.x, first.y + second.y) result = Vector2D(8, 16) result.x = 8 result.y = 16
15th Jul 2018, 12:26 PM
Seb TheS
Seb TheS - avatar
0
can you plz explain about what's happening with the parameteres
15th Jul 2018, 9:11 AM
adarsh pandey
adarsh pandey - avatar
0
thanks sir
15th Jul 2018, 9:19 AM
adarsh pandey
adarsh pandey - avatar
0
thanks sir
15th Jul 2018, 10:30 AM
adarsh pandey
adarsh pandey - avatar