我正在为模块级别的构造创建一个enter / exit块。我有以下示例测试如何从类中访问模块级变量:
_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__()
是否正确且是一种好的做法?
答案 0 :(得分:3)
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