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


当前回答

我一直认为这与python的禅意有关:

应该有一种——最好只有一种——明显的方法来做到这一点。

x++和X +=1做的是完全相同的事情,所以没有理由同时拥有两者。

其他回答

我对python很陌生,但我怀疑原因是因为语言中可变对象和不可变对象之间的强调。现在,我知道x++可以很容易地解释为x = x+ 1,但它看起来像你在原地递增一个对象,而这个对象可能是不可变的。

这只是我的猜测/感觉/预感。

我一直认为这与python的禅意有关:

应该有一种——最好只有一种——明显的方法来做到这一点。

x++和X +=1做的是完全相同的事情,所以没有理由同时拥有两者。

Maybe a better question would be to ask why do these operators exist in C. K&R calls increment and decrement operators 'unusual' (Section 2.8page 46). The Introduction calls them 'more concise and often more efficient'. I suspect that the fact that these operations always come up in pointer manipulation also has played a part in their introduction. In Python it has been probably decided that it made no sense to try to optimise increments (in fact I just did a test in C, and it seems that the gcc-generated assembly uses addl instead of incl in both cases) and there is no pointer arithmetic; so it would have been just One More Way to Do It and we know Python loathes that.

因为,在Python中,整数是不可变的(int's +=实际上返回一个不同的对象)。

同样,使用++/——,您需要考虑前后的递增/递减,并且只需要多击一次键就可以写出x+=1。换句话说,它以很少的收益为代价避免了潜在的混乱。

我最初写的这个答案是一个来自计算机民间传说的神话:丹尼斯·里奇(Dennis Ritchie)在2012年7月给ACM通讯编辑的信中指出,它被揭穿为“历史上不可能的”doi:10.1145/2209249.2209251


C加/减操作符是在C编译器还不是很聪明的时候发明的,作者希望能够指定应该使用机器语言操作符的直接意图,这为编译器节省了一些周期

load memory
load 1
add
store memory

而不是

inc memory 

PDP-11甚至支持“自动递增”和“自动递增延迟”指令,分别对应于*++p和*p++。如果非常好奇,请参阅手册5.3节。

由于编译器足够聪明,可以处理C语法中内置的高级优化技巧,所以它们现在只是语法上的便利。

Python没有向汇编器传递意图的技巧,因为它不使用这些技巧。