I always though that using the "+" operator in Python (3.5) calls the __add__ method under the hood and return the sum. However, I noticed some quirky behavior when negative numbers are involved. Naturally,
>>>-3 + 7
returns 4
But(!)
>>>-3 .__add__(7)
returns -10 and
>>>-3 .__add__(-7)
4
>>>3 .__add__(7)
10
Is there a reason why __add__ signs the arguments if the object is signed. Also, what changes in the method so that when I use "+", the "correct" value comes out?
- is an operator too, an unary one. You called __add__ on 3, not on the result of - applied to 3, because attribute access binds more tightly than the - operator.
Use parentheses:
>>> (-3).__add__(7)
4
Your code applies the - unary operator to the result of 3 + 7 instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With