为什么Python中没有++和——运算符?
当前回答
除了这里的其他优秀答案之外,++和——也因未定义的行为而臭名昭著。例如,这段代码中发生了什么?
foo[bar] = bar++;
它看起来很无辜,但它是错误的C(和c++),因为您不知道第一个栏是否会增加。一个编译器可能会以一种方式执行,另一个可能会以另一种方式执行,而第三个编译器可能会让恶魔从你的鼻子里飞出来。所有这些都完全符合C和c++标准。
(编辑:c++ 17改变了给定代码的行为,这样它就被定义了;它将等价于foo[bar+1] = bar;+ +酒吧;——尽管如此,这可能不是程序员所期望的。)
在C和c++中,未定义行为被视为不可避免的邪恶,但在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的快捷方式。Python通常采用一种设计策略,减少执行操作的可选方法的数量。增强赋值是Python中最接近自增/自减操作符的东西,它们直到Python 2.0才被添加。
这并不是因为它没有意义;将“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 -=).
这些都是+=和-=的冗余,所以会变成净损失。
操作符的++类是带有副作用的表达式。这在Python中通常是找不到的。
出于同样的原因,赋值在Python中不是表达式,从而防止使用here */}习语来使用常见的if (a = f(…)){/*。
最后,我怀疑这些操作符与python的引用语义不太一致。请记住,Python没有C/ c++中已知语义的变量(或指针)。
其他答案描述了为什么迭代器不需要它,但有时它在赋值以inline增加变量时很有用,你可以使用元组和多次赋值达到相同的效果:
B = ++a变成:
a,b = (a+1,)*2
b = a++变成:
a,b = a+1, a
Python 3.8引入了赋值:=操作符,允许我们用
foo(a:=a+1)
Foo (a++)仍然是难以捉摸的。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录