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


当前回答

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

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

其他回答

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

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

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

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

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

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

让我们假设我们决定这样做,前缀(++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