代码之家  ›  专栏  ›  技术社区  ›  David Parks

“global”是类访问模块级变量的正确方法吗?

  •  0
  • David Parks  · 技术社区  · 6 年前

    我正在为模块级构造创建一个进入/退出块。我有以下示例来测试如何从类中访问模块级变量:

    _variableScope = ''
    
    class VariableScope(object):
      def __init__(self, scope):
        self._scope = scope
    
      def __enter__(self):
        global _variableScope
        _variableScope += self._scope
    
    x = VariableScope('mytest')
    x.__enter__()
    print(_variableScope)
    

    这就得到了 'mytest' ,但是。。。

    是使用 global 内部 __enter__()

    1 回复  |  直到 6 年前
        1
  •  3
  •   Prune    6 年前

    global 是一种“代码气味”:表示不需要的代码设计的东西。在本例中,您只是尝试为类的所有实例创建一个资源。首选策略是 class attribute

    class VariableScope():
        _variableScope = ''
    
        def __init__(self, scope):
            self._scope = scope
    
        def __enter__(self):
            VariableScope._variableScope += self._scope
    
    x = VariableScope('mytest')
    x.__enter__()
    print(VariableScope._variableScope)
    
    y = VariableScope('add-to-scope')
    y.__enter__()
    print(VariableScope._variableScope)
    

    输出:

    mytest
    mytestadd-to-scope