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


当前回答

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

其他回答

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

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

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

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

我知道这是一个旧线程,但最常见的用例++ I没有涵盖,即手动索引集时,没有提供索引。这种情况就是python提供enumerate()的原因

示例:在任何给定的语言中,当你使用像foreach这样的构造来遍历一个集合时——为了示例的目的,我们甚至会说它是一个无序的集合,你需要一个唯一的索引来区分它们

i = 0
stuff = {'a': 'b', 'c': 'd', 'e': 'f'}
uniquestuff = {}
for key, val in stuff.items() :
  uniquestuff[key] = '{0}{1}'.format(val, i)
  i += 1

在这种情况下,python提供了一个枚举方法,例如。

for i, (key, val) in enumerate(stuff.items()) :

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

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

我相信这源于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.