Argument passing to __add__ magic method | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Argument passing to __add__ magic method

Hello dear coders, Could you please advice how the value of a is passed to the “+” operator (actually __add__ method) in the following code: class malicious(int): def __init__(self, value): pass def __add__(self, x): res = self // x return res a = malicious(5) print(3+a) #Output: 8 I know that the add method of the class isn’t working here as I stated 3+a not a+3, but it is unclear how the value of the a is seen and passed by to the usual + operator.

21st Jan 2023, 7:13 PM
Ruslan Guliyev
Ruslan Guliyev - avatar
2 Answers
+ 3
malicious is a subclass of int, so the instance "a" still represents a number. When you use the operation 3+a then first python is checking if addition is defined for the left operand (3) as this is just a normal number, the default addition is used. You would get a different result if you calculate a+3 because malicious class has overwritten this operator. Additionally if the __add__ magic method is not defined for the object on the left side of the + sign, then Python still checks if you have __radd__ (right addition) defined for the object on the right side. If this doesn't work either, you get an error.
21st Jan 2023, 7:49 PM
Tibor Santa
Tibor Santa - avatar
0
Tibor Santa, thanks a lot, it is very comperehensive answer! Could you please explain how the 5 is passed to the __add__ method of int class? I even didn’t stated that self.value = value, but it is directly passed to the function. This part is the last dark point for me.
23rd Jan 2023, 9:42 AM
Ruslan Guliyev
Ruslan Guliyev - avatar