Python全局变量的替代方法 [英] An alternative to global in Python

查看:60
本文介绍了Python全局变量的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有这样的代码:

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

但是,这可能会在将来导致难以发现的错误,因为读者可能不会注意到global cache出现在cache = 2上方的某个地方.或者,贡献者可能会错误地添加def bar(): cache = 2而忘记添加global cache.

However, this may lead to hard-to-find-bugs in the future, because the reader may not notice that global cache appears somewhere above cache = 2. Alternatively, a contributor may mistakenly add def bar(): cache = 2 and forget to add the global cache.

如何避免这种陷阱?

推荐答案

class Cache:
     myvar = 1

def foo():
    Cache.myvar = 2

这样,Cache.myvar实际上是一个全局".可以从任何地方对其进行读写.

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.

这篇关于Python全局变量的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆