Python: function attributes inside a class | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Python: function attributes inside a class

class Vec: def __init__ (self,x,y): self.x=x print(self.x) print("=====x=====") self.y=y print(self.y) print("=====y=====") def __add__ (self,other): print(other.x) ### how did we get to the value 1 here? print("=====xxx=====") print(other.y). ### how did we get to the value 2 here? print("=====yyy=====") return Vec(self.x+other.x,self.y+other.y) <-- *** v1=Vec(3,4) v2=Vec(1,2) r=v1+v2 print(r.x+r.y) ###outputs 10 *** I don't really understand why other.x and other.y has v2's values (while self.x and self.y has v1's values).

15th Sep 2020, 7:44 PM
Solus
Solus - avatar
1 Answer
+ 5
v1 + v2 invokes the v1.__add__(v2) magic method. So v1 is the "self" part and v2 is the "other" part. If it were the other way... v2 + v1 would invoke v2.__add__(v1).
15th Sep 2020, 8:19 PM
Russ
Russ - avatar