Python Quiz help | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
0

Python Quiz help

class Number(): def __init__(self, n): self.n = n def __add__(self, other): return self.n - other.n a = Number(4) b = Number(2) print(a+b) //answer is 2 Above code is one of the quizzes in the challenge. However, I do not understand how the answer comes to 2. How is the __add__ function get called? I know the __init__ gets called once an instance is initiated. Does that apply to __add__ function as well? Also, what is being passed as a parameter for “other” in __add__ function?

14th Nov 2021, 2:09 AM
Han Lee
Han Lee - avatar
1 Respuesta
+ 4
The __add__ method is called by using the plus sign. It's called a "magic method". Whenever you combine two objects of a particular class with the plus sign the __add__ method of that class is called. For float and int __add__ performs addition, for string it performs concatenation, etc. In your case the __add__ method of the class Number performs subtraction. The first object passed to it is referred to as "self" in the definition, the second as "other". These are arbitrary names, but it is a strongly recommended convention to call them "self" and "other". So when you use a + b, a is self and b is other. So the function returns a - b, in this case 4 - 2 = 2.
14th Nov 2021, 2:19 AM
Simon Sauter
Simon Sauter - avatar