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


当前回答

我一直认为这与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.

我认为这与对象的可变性和不变性的概念有关。2,3,4,5在python中是不可变的。参考下图。2在此python进程之前有固定的id。

x++本质上意味着像C一样的原地增量。在C中,x++执行原地增量。因此,x=3, x++会将内存中的3增加到4,不像python中的3仍然存在于内存中。

因此,在python中,你不需要在内存中重新创建一个值。这可能会导致性能优化。

这是一个基于直觉的答案。

这可能是因为@GlennMaynard将这个问题与其他语言进行了比较,但在Python中,你用Python的方式做事。这不是一个“为什么”的问题。它在这里,你可以用x+=做同样的事情。在Python的禅宗中,它被赋予:“应该只有一种方法来解决一个问题。”多重选择在艺术上很好(表达自由),但在工程上很糟糕。

当然,我们可以说“Guido只是决定那样做”,但我认为问题实际上是关于这个决定的原因。我认为有以下几个原因:

它将语句和表达式混合在一起,这不是好的实践。参见http://norvig.com/python-iaq.html 它通常鼓励人们编写可读性较差的代码 语言实现中的额外复杂性,如前所述,这在Python中是不必要的

我相信这源于Python的信条“显式优于隐式”。