Behaviour of increment and decrement operators in Python

后端 未结 9 2047
无人共我
无人共我 2020-11-22 05:26

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 vari

9条回答
  •  猫巷女王i
    2020-11-22 05:49

    When you want to increment or decrement, you typically want to do that on an integer. Like so:

    b++
    

    But in Python, integers are immutable. That is you can't change them. This is because the integer objects can be used under several names. Try this:

    >>> b = 5
    >>> a = 5
    >>> id(a)
    162334512
    >>> id(b)
    162334512
    >>> a is b
    True
    

    a and b above are actually the same object. If you incremented a, you would also increment b. That's not what you want. So you have to reassign. Like this:

    b = b + 1
    

    Or simpler:

    b += 1
    

    Which will reassign b to b+1. That is not an increment operator, because it does not increment b, it reassigns it.

    In short: Python behaves differently here, because it is not C, and is not a low level wrapper around machine code, but a high-level dynamic language, where increments don't make sense, and also are not as necessary as in C, where you use them every time you have a loop, for example.

提交回复
热议问题