Python中递增和递减运算符的行为 [英] Behaviour of increment and decrement operators in Python

查看:250
本文介绍了Python中递增和递减运算符的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到可以对变量(如++count)应用预增/减运算符.它可以编译,但实际上并不会改变变量的值!

I notice that a pre-increment/decrement operator can be applied on a variable (like ++count). It compiles, but it does not actually change the value of the variable!

Python中预增/减算符(++/-)的行为是什么?

What is the behavior of the pre-increment/decrement operators (++/--) in Python?

为什么Python会偏离C/C ++中看到的这些运算符的行为?

Why does Python deviate from the behavior of these operators seen in C/C++?

推荐答案

++不是运算符.它是两个+运算符. +运算符是 identity 运算符,它不执行任何操作. (澄清:+-一元运算符仅适用于数字,但我想您不会期望假设的++运算符适用于字符串.)

++ is not an operator. It is two + operators. The + operator is the identity operator, which does nothing. (Clarification: the + and - unary operators only work on numbers, but I presume that you wouldn't expect a hypothetical ++ operator to work on strings.)

++count

解析为

+(+count)

翻译为

count

您必须使用稍长的+=运算符来执行您想做的事情:

You have to use the slightly longer += operator to do what you want to do:

count += 1

我怀疑++--运算符出于一致性和简单性而被遗漏了.我不知道Guido van Rossum做出决定的确切论据,但我可以想像一些论点:

I suspect the ++ and -- operators were left out for consistency and simplicity. I don't know the exact argument Guido van Rossum gave for the decision, but I can imagine a few arguments:

  • 更简单的解析.从技术上讲,解析++count是模棱两可的,因为解析可能是++count(两个一元+运算符),就像解析++count(一个一元++运算符).这不是明显的句法歧义,但确实存在.
  • 简单的语言. ++只不过是+= 1的同义词.这是一种速记方法,因为C编译器很愚蠢,并且不知道如何将a += 1优化为大多数计算机具有的inc指令.在优化编译器和字节码解释语言的这一天,通常不赞成在一种语言中添加运算符以允许程序员优化其代码,尤其是在像Python这样设计成一致且易读的语言中.
  • 令人困惑的副作用.使用++运算符的语言中一个常见的新手错误是混合使用递增/递减运算符之间的差异(优先级和返回值),Python喜欢消除语言陷阱". 优先问题 /a/17819123/1449799> C中的前/后递增非常繁琐,而且非常容易弄乱.
  • Simpler parsing. Technically, parsing ++count is ambiguous, as it could be +, +, count (two unary + operators) just as easily as it could be ++, count (one unary ++ operator). It's not a significant syntactic ambiguity, but it does exist.
  • Simpler language. ++ is nothing more than a synonym for += 1. It was a shorthand invented because C compilers were stupid and didn't know how to optimize a += 1 into the inc instruction most computers have. In this day of optimizing compilers and bytecode interpreted languages, adding operators to a language to allow programmers to optimize their code is usually frowned upon, especially in a language like Python that is designed to be consistent and readable.
  • Confusing side-effects. One common newbie error in languages with ++ operators is mixing up the differences (both in precedence and in return value) between the pre- and post-increment/decrement operators, and Python likes to eliminate language "gotcha"-s. The precedence issues of pre-/post-increment in C are pretty hairy, and incredibly easy to mess up.

这篇关于Python中递增和递减运算符的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆