+ 1
class Vector2D: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return
please someone should help me correct the errors I made here and indicate what you have done to make it run successfully
2 Answers
+ 2
So let's say that you have your (x,y) coordinates (5,4) and you want to add a number (3) to both of them (output (8,7)):
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
# On return add other to both x and y
def __add__(self, other):
return self.x + other, self.y + other
# Create an instance of the class with the initial values
a = Vector2D(5,4)
# add 3 to both x and y and print
print(a+3)
0
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)
I also was didn't understand this code,but i referred some youtube videos and finally, i try to explain you at my best level.
in the second function of above code
def __add__(self,other): #the self and other are act as two variables,if you want you can the change the variable name. As example def __add__(K,D)
For those who didnt get this line,
self.x =5 ,self.y =7 and self.y =3,other.y =9
#in case you changed the name of variable then dont forget to update this line.
We take our previous example :- return Vector2D(K.x + D.x, K.y + D.y)
if i did any mistake while explaining this code,please correct me.
i hope you got the idea about this code,Thank You.