def PreIncrement(name, local={}):#Equivalent to ++nameif name in local:local[name]+=1return local[name]globals()[name]+=1return globals()[name]
def PostIncrement(name, local={}):#Equivalent to name++if name in local:local[name]+=1return local[name]-1globals()[name]+=1return globals()[name]-1
用法:
x = 1y = PreIncrement('x') #y and x are both 2a = 1b = PostIncrement('a') #b is 1 and a is 2
x = 1def test():x = 10y = PreIncrement('x') #y will be 2, local x will be still 10 and global x will be changed to 2z = PreIncrement('x', locals()) #z will be 11, local x will be 11 and global x will be unalteredtest()
还有这些功能,你可以做:
x = 1print(PreIncrement('x')) #print(x+=1) is illegal!
但在我看来,以下方法更清晰:
x = 1x+=1print(x)
递减操作员:
def PreDecrement(name, local={}):#Equivalent to --nameif name in local:local[name]-=1return local[name]globals()[name]-=1return globals()[name]
def PostDecrement(name, local={}):#Equivalent to name--if name in local:local[name]-=1return local[name]+1globals()[name]-=1return globals()[name]+1