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


当前回答

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

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

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

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

其他回答

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.

这并不是因为它没有意义;将“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 -=).

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

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

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

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

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

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

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

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

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