为什么Python中没有++和——运算符?


当前回答

这并不是因为它没有意义;将“x++”定义为“x+ = 1,求值到x的前一个绑定”非常有意义。

如果你想知道最初的原因,你必须在旧的Python邮件列表中寻找,或者询问当时在那里的人(例如。Guido),但事后很容易就能证明:

简单的递增和递减不需要像其他语言那样多。你不会写这样的for(int i = 0;I < 10;i)在Python中经常使用;相反,你可以把I放在(0,10)范围内。

由于不经常需要它,所以没有理由给它自己的特殊语法;当您确实需要增加时,+=通常就可以了。

It's not a decision of whether it makes sense, or whether it can be done--it does, and it can. It's a question of whether the benefit is worth adding to the core syntax of the language. Remember, this is four operators--postinc, postdec, preinc, predec, and each of these would need to have its own class overloads; they all need to be specified, and tested; it would add opcodes to the language (implying a larger, and therefore slower, VM engine); every class that supports a logical increment would need to implement them (on top of += and -=).

这些都是+=和-=的冗余,所以会变成净损失。

其他回答

清晰!

Python非常强调清晰度,没有程序员能够正确地猜出——a的含义,除非他/她学过一种具有这种结构的语言。

Python还在很大程度上避免了引起错误的构造,而++操作符是众所周知的缺陷的丰富来源。 这两个原因足以让Python中不使用这些操作符。

决定Python使用缩进来标记块而不是 而不是句法手段,比如某种形式的开始/结束括号 或者强制性的结束标记很大程度上是基于同样的考虑。

为了说明问题,我们来看看关于引入条件操作符的讨论(在C: cond ?resultif: resultelse)在2005年加入Python。 至少阅读该讨论的第一条信息和决定信息(前面有几个关于同一主题的前奏)。

花絮: 其中经常提到的PEP是“Python增强提案”PEP 308。LC表示列表理解,GE表示生成器表达式(如果这些使您感到困惑,请不要担心,它们不是Python中少数复杂的地方)。

要完成那一页上已经很好的答案:

让我们假设我们决定这样做,前缀(++i)将打破一元的+和-操作符。

现在,用++或——作为前缀没有任何作用,因为它使一元加运算符两次(没有任何作用)或一元减运算符两次(两次:取消自身)

>>> i=12
>>> ++i
12
>>> --i
12

所以这可能会打破这个逻辑。

现在,如果需要它来进行列表推导或lambdas,从python 3.8开始,可以使用新的:=赋值操作符(PEP572)

预递增a并赋值给b:

>>> a = 1
>>> b = (a:=a+1)
>>> b
2
>>> a
2

后增量只需要通过减1来弥补过早的加法:

>>> a = 1
>>> b = (a:=a+1)-1
>>> b
1
>>> a
2

它就是这样设计的。自增和自减运算符只是x = x + 1的快捷方式。Python通常采用一种设计策略,减少执行操作的可选方法的数量。增强赋值是Python中最接近自增/自减操作符的东西,它们直到Python 2.0才被添加。

这并不是因为它没有意义;将“x++”定义为“x+ = 1,求值到x的前一个绑定”非常有意义。

如果你想知道最初的原因,你必须在旧的Python邮件列表中寻找,或者询问当时在那里的人(例如。Guido),但事后很容易就能证明:

简单的递增和递减不需要像其他语言那样多。你不会写这样的for(int i = 0;I < 10;i)在Python中经常使用;相反,你可以把I放在(0,10)范围内。

由于不经常需要它,所以没有理由给它自己的特殊语法;当您确实需要增加时,+=通常就可以了。

It's not a decision of whether it makes sense, or whether it can be done--it does, and it can. It's a question of whether the benefit is worth adding to the core syntax of the language. Remember, this is four operators--postinc, postdec, preinc, predec, and each of these would need to have its own class overloads; they all need to be specified, and tested; it would add opcodes to the language (implying a larger, and therefore slower, VM engine); every class that supports a logical increment would need to implement them (on top of += and -=).

这些都是+=和-=的冗余,所以会变成净损失。

正如我理解的那样,你不会认为内存中的值被改变了。 在c语言中,当你执行x++时,内存中的x值会发生变化。 但在python中,所有数字都是不可变的,因此x指向的地址仍然是x而不是x+1。当你写x++时,你会认为x改变了,实际上发生的是x引用被改变到内存中存储x+1的位置,或者如果doe不存在,重新创建这个位置。