Behaviour of increment and decrement operators in Python

后端 未结 9 1865
无人共我
无人共我 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条回答
  •  攒了一身酷
    2020-11-22 05:56

    TL;DR

    Python does not have unary increment/decrement operators (--/++). Instead, to increment a value, use

    a += 1
    

    More detail and gotchas

    But be careful here. If you're coming from C, even this is different in python. Python doesn't have "variables" in the sense that C does, instead python uses names and objects, and in python ints are immutable.

    so lets say you do

    a = 1
    

    What this means in python is: create an object of type int having value 1 and bind the name a to it. The object is an instance of int having value 1, and the name a refers to it. The name a and the object to which it refers are distinct.

    Now lets say you do

    a += 1
    

    Since ints are immutable, what happens here is as follows:

    1. look up the object that a refers to (it is an int with id 0x559239eeb380)
    2. look up the value of object 0x559239eeb380 (it is 1)
    3. add 1 to that value (1 + 1 = 2)
    4. create a new int object with value 2 (it has object id 0x559239eeb3a0)
    5. rebind the name a to this new object
    6. Now a refers to object 0x559239eeb3a0 and the original object (0x559239eeb380) is no longer refered to by the name a. If there aren't any other names refering to the original object it will be garbage collected later.

    Give it a try yourself:

    a = 1
    print(hex(id(a)))
    a += 1
    print(hex(id(a)))
    

提交回复
热议问题