IgnasFunka
IgnasFunka

Reputation: 90

__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?

Upvotes: 3

Views: 285

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121924

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

Upvotes: 8

Adah
Adah

Reputation: 113

.__add__ is an operation between two objects so 3.add(7) = 10; -3.add(7) is like calling add for 3 and 7 and then applying (-) as an operator So -(10) as a result You need to use parentheses to get the proper operation

Upvotes: 1

Related Questions