简体   繁体   English

__add__方法和Python中的负数

[英]__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. 我总是在Python(3.5)中使用“+”运算符调用引擎下的__add__方法并返回总和。 However, I noticed some quirky behavior when negative numbers are involved. 但是,当涉及负数时,我注意到一些古怪的行为。 Naturally, 自然,

>>>-3 + 7

returns 4 返回4

But(!) 但(!)

>>>-3 .__add__(7)

returns -10 and 返回-10和

>>>-3 .__add__(-7)
4
>>>3 .__add__(7)
10

Is there a reason why __add__ signs the arguments if the object is signed. 如果对象被签名,是否有__add__签署参数的原因。 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 . 你叫__add__3 ,而不是结果-适用于3 ,因为属性的访问比结合更紧密-运营商

Use parentheses: 使用括号:

>>> (-3).__add__(7)
4

Your code applies the - unary operator to the result of 3 + 7 instead. 您的代码将-一元运算符应用于3 + 7的结果。

.__add__ is an operation between two objects so 3. add (7) = 10; .__add__是两个对象之间的操作,所以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 -3.add(7)就像调用add for 3和7然后应用( - )作为运算符所以 - (10)作为结果你需要使用括号来获得正确的操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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