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