简体   繁体   English

为什么 Python 将加法运算符的连续重复视为一次重复?

[英]Why does Python treat consecutive repetitions of the addition operator as just a single repetition?

Today I noticed that the Python interpreter treats consecutive repetitions of the addition operator as just one repetition of the operator.今天我注意到 Python 解释器将加法运算符的连续重复视为运算符的重复。 For example:例如:

>>> 1 ++ 2
3

Of what use was it to not simply raise an error when such an event occurs?当这样的事件发生时,不简单地引发错误有什么用? I find it much more believable that a programmer who typed我发现打字的程序员更可信

>>> 1 -+-++ 2

was just out of their mind;只是疯了; it would be highly unlikely that this ever intentionally appears in code.这不太可能故意出现在代码中。

It seems to serve no purpose, for writing something like它似乎没有任何目的,因为写了类似的东西

>>> +-1

simply returns -1 , demonstrating that the operation does not make the number positive, rather, it simply performs the identity operation.简单地返回-1 ,表明该操作不会使数字为正数,而是简单地执行恒等操作。

Because it's overloaded.因为超载了。 It's the addition operator (implemented by the __add__ method), and also the unary positive operator (implemented by __pos__ ).它是加法运算符(由__add__方法实现),也是一元正运算符(由__pos__实现)。 Compare that to - , which is the subtraction operator ( __sub__ ) and unary negative operator ( __neg__ ).将其与-进行比较,它是减法运算符 ( __sub__ ) 和一元负运算符 ( __neg__ )。

So for example, 1 ++ 2 is parsed as 1 + (+ 2) which simplifies down to 1 + 2 for integers, but not necessarily for other types.因此,例如, 1 ++ 2被解析为1 + (+ 2) ,这将整数简化为1 + 2 ,但对于其他类型则不一定。 See What's the purpose of the + (pos) unary operator in Python?请参阅Python 中 + (pos) 一元运算符的用途是什么?

It's mathematical.这是数学的。 While it doesn't make sense to a normal person, to python +(+1) and -(-1) is +, +(-1) and -(+1) is -.虽然这对普通人没有意义,但对于 python +(+1) 和 -(-1) 是 +,+(-1) 和 -(+1) 是 -。 Jumping back into the question, it isn't just python that does this.回到这个问题,不仅仅是 python 这样做了。 It's mathematical thinking.是数学思维。 It's like telling a computer a variable called string is equal to 29. It sounds wrong but the computer thinks it is normal.这就像告诉计算机一个名为 string 的变量等于 29。这听起来不对,但计算机认为这是正常的。

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

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