+ 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)
7 odpowiedzi
+ 2
hey adarsh pandey
here '+' operator is overloaded to add two objects of type Vector2D
this is called polymorphism.
+ 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)
+ 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
+ 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
0
can you plz explain about what's happening with the parameteres
0
thanks sir
0
thanks sir