为什么Python中没有++和——运算符?
当前回答
这并不是因为它没有意义;将“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中,整数是不可变的(int's +=实际上返回一个不同的对象)。
同样,使用++/——,您需要考虑前后的递增/递减,并且只需要多击一次键就可以写出x+=1。换句话说,它以很少的收益为代价避免了潜在的混乱。
我对python很陌生,但我怀疑原因是因为语言中可变对象和不可变对象之间的强调。现在,我知道x++可以很容易地解释为x = x+ 1,但它看起来像你在原地递增一个对象,而这个对象可能是不可变的。
这只是我的猜测/感觉/预感。
当然,我们可以说“Guido只是决定那样做”,但我认为问题实际上是关于这个决定的原因。我认为有以下几个原因:
它将语句和表达式混合在一起,这不是好的实践。参见http://norvig.com/python-iaq.html 它通常鼓励人们编写可读性较差的代码 语言实现中的额外复杂性,如前所述,这在Python中是不必要的
首先,Python只是间接地受到C的影响;它深受ABC的影响,ABC显然没有这些操作符,所以在Python中找不到它们也不足为奇。
其次,正如其他人所说,递增和递减已经由+=和-=支持。
第三,对++和——操作符集的完全支持通常包括对它们的前缀和后缀版本的支持。在C和c++中,这可能会导致各种“可爱的”构造,这些构造(对我来说)似乎违背了Python所信奉的简单和直接的精神。
例如,while C语句while(*t++ = *s++);对于一个有经验的程序员来说,它可能看起来简单而优雅,但对于一个初学者来说,它一点也不简单。加上前缀和后缀的增量和减量的混合,甚至许多专业人士也不得不停下来思考一下。
这并不是因为它没有意义;将“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 -=).
这些都是+=和-=的冗余,所以会变成净损失。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获得所有直接子目录