简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM