What does this code meansand how second digits add to the first one? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What does this code meansand how second digits add to the first one?

https://code.sololearn.com/cOKjzTFULCQW/?ref=app

20th Nov 2019, 10:29 PM
Ansab Khan
Ansab Khan - avatar
7 Answers
0
Ansab Khan "other" is the argument of the function __add__(). As it was already explained, first + second is the same as... first.__add__(second) So "second" variable is passed in "other" argument. So "other.x" is "second.x"... I hope that's a good enough explanation!
21st Nov 2019, 8:11 AM
Gonçalo Magalhaes
Gonçalo Magalhaes - avatar
+ 2
The __add__() is just a method that gets called when you use the "+" sign. think of..... result = first + second as being.... result = first.__add__(seconds). side note. Even though the "add" word is there, there nothing stopping you doing anything you like in the "__add__()" method, e.g. print something, multiply something... etc.
20th Nov 2019, 10:34 PM
rodwynnejones
rodwynnejones - avatar
+ 1
thanks Gonçalo Magalhaes got it.👍👍
21st Nov 2019, 8:18 AM
Ansab Khan
Ansab Khan - avatar
0
What rodwynnejones said is right. In the example, "second" will passed as "other" to the __add__() method. This way Python allows your objects to have new rules on how to add, subtract, multiply, etc. Considering the Vectors example, one could see the point of rewriting the use of len(). To do that, you write the __len__() method just like __add__() but without the "other" param, and you can return something like sqrt(self.x**2 + self.y**2). There are other methods such as __len__ and __add__, which will give a lot fo power to your objects.
21st Nov 2019, 12:09 AM
Gonçalo Magalhaes
Gonçalo Magalhaes - avatar
0
rodwynnejones and Gonçalo Magalhaes how the (other.x) takes the 2nd number from secone variable? because in this we didnt define other variable
21st Nov 2019, 1:56 AM
Ansab Khan
Ansab Khan - avatar
0
Ansab Khan __add__() is called magic method. This function is use to add two objects. If you are giving parameter to __add__() method means you are giving objects to __add__() method. Here first and second is your object. You are giving first as self and second as other parameter to __add__() method. self.x means first argument of the first object which is 5 and self.y is the second argument of the self object which is 7 and same for other object. When you add self.x and other.x you got 8 because self.x is 5 and other.x is 3 and same for self.y+other.y
21st Nov 2019, 2:23 AM
Maninder $ingh
Maninder $ingh - avatar
0
Maninder $ingh so the "other" object is default?? because we didn't took or define "other" object
21st Nov 2019, 8:03 AM
Ansab Khan
Ansab Khan - avatar