在python中,++ x是正确的语法。

in python, ++x is correct syntax. What does “++x” mean?

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
Python: Behaviour of increment and decrement operators

1
2
3
4
5
6
7
8
9
10
>>> a=2
>>> ++a
2
>>> a++
Traceback (  File"<interactive input>", line 1
    a++
      ^
SyntaxError: invalid syntax
>>> ++a
2

为什么++X可以?

(我问的是,因为工作中的某个人习惯性地写了++I,这并没有(习惯性地)预期的那样做,但也没有抛出错误,所以花了一些时间才发现错误。)


它的意思是+(+a),即与-(-a)的意思相反(虽然在这种情况下,结果显然是相同的!)

请参见http://docs.python.org/library/stdtypes.html numeric types int float long complex。


相当于+(+a)

1
2
3
4
5
6
7
8
>>> +-2
-2
>>> -+2
-2
>>> --2
2
>>> ++++-2
-2


python的可能副本:递增和递减运算符的行为。

虽然我找不到有关操作员确切推理的文件,但我将引用我认为是这种情况的关联问题中已接受答案的一部分:

  • 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.