0

Explain please. What does other.x means

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) output >>> 8 >>> 16

27th Dec 2016, 8:41 PM
Djaber Meghar
Djaber Meghar - avatar
3 Answers
+ 3
# If you understand that 'other' # represents an instance then, # To address your question directly other.x # means get the value x of the instance I am passing in # as one of the arguments on the call to __add__ # It might help to look at it this way. #'other' is just a parameter to represent a class instance. #just as 'self' is representative of a class instance . #If you want to think about what is really going on here #in this specific example you can imagine it like this by changing the code #to mimic the instance names. class Vector2D: def __init__(first, x, y): first.x = x first.y = y def __add__(first, second): return Vector2D(first.x + second.x, first.y + second.y) # instance of a Vector2D class object first = Vector2D(5, 7) # another of a Vector2D class object second = Vector2D(3, 9) result = first + second # results of addition using the class method print(result.x) print(result.y) # the code gives the same result as the original showing that # the parameter names can be anything. # They are just representing the two class instances. #However! other than when you are trying # to figure out ,while learning ,how class methods work and # what 'self' or 'other.x' might mean stick to using # self and meaningful names in class methods you construct because it is # convention to do and once you understand # the process it makes a lot more sense to do so.
27th Dec 2016, 10:23 PM
richard
0
Other Vector2D object
27th Dec 2016, 9:53 PM
Jakub Stasiak
Jakub Stasiak - avatar
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.
29th Apr 2020, 1:53 PM
Kuldeepak Anand Pawar
Kuldeepak Anand Pawar - avatar