Behaviour of increment and decrement operators in Python

后端 未结 9 2062
无人共我
无人共我 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:53

    Python does not have these operators, but if you really need them you can write a function having the same functionality.

    def PreIncrement(name, local={}):
        #Equivalent to ++name
        if name in local:
            local[name]+=1
            return local[name]
        globals()[name]+=1
        return globals()[name]
    
    def PostIncrement(name, local={}):
        #Equivalent to name++
        if name in local:
            local[name]+=1
            return local[name]-1
        globals()[name]+=1
        return globals()[name]-1
    

    Usage:

    x = 1
    y = PreIncrement('x') #y and x are both 2
    a = 1
    b = PostIncrement('a') #b is 1 and a is 2
    

    Inside a function you have to add locals() as a second argument if you want to change local variable, otherwise it will try to change global.

    x = 1
    def test():
        x = 10
        y = PreIncrement('x') #y will be 2, local x will be still 10 and global x will be changed to 2
        z = PreIncrement('x', locals()) #z will be 11, local x will be 11 and global x will be unaltered
    test()
    

    Also with these functions you can do:

    x = 1
    print(PreIncrement('x'))   #print(x+=1) is illegal!
    

    But in my opinion following approach is much clearer:

    x = 1
    x+=1
    print(x)
    

    Decrement operators:

    def PreDecrement(name, local={}):
        #Equivalent to --name
        if name in local:
            local[name]-=1
            return local[name]
        globals()[name]-=1
        return globals()[name]
    
    def PostDecrement(name, local={}):
        #Equivalent to name--
        if name in local:
            local[name]-=1
            return local[name]+1
        globals()[name]-=1
        return globals()[name]+1
    

    I used these functions in my module translating javascript to python.

提交回复
热议问题