Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__add__ method and negative numbers in Python

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?

like image 591
IgnasFunka Avatar asked Dec 16 '25 14:12

IgnasFunka


1 Answers

- 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.

like image 187
Martijn Pieters Avatar answered Dec 19 '25 06:12

Martijn Pieters