An alternative to global in Python

前端 未结 4 1756
轮回少年
轮回少年 2020-12-19 05:58

I currently have code like this:

cache = 1
def foo():
    global cache
    # many
    # lines
    # of code
    cache = 2

However, this may

4条回答
  •  攒了一身酷
    2020-12-19 06:42

    class Cache:
         myvar = 1
    
    def foo():
        Cache.myvar = 2
    

    This way, Cache.myvar is practically a "global". It's possible to read/write to it from anywhere.

    I prefer this over the dictionary alternative, because it allows for auto-complete of the variable names.

提交回复
热议问题