[英]Is `global` the correct way for a class to access a module level variable?
我正在為模塊級構造創建一個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'
的期望值,但是...
__enter__()
方法內部使用global
是否正確且是好的做法?
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.