首页 > 解决方案 > `global` 是类访问模块级变量的正确方法吗?

问题描述

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

_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',但是......

使用globalinside__enter__()方法是否正确和良好的做法?

标签: python

解决方案


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

推荐阅读