python - `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'
,但是......
使用global
inside__enter__()
方法是否正确和良好的做法?
解决方案
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
推荐阅读
- javascript - 文件夹中的动态幻灯片
- c# - File.ReadAllLines 将可执行路径添加到提供的路径
- c++ - 关于识别方法签名存在的 C++ 自省
- mysql - 为什么在安装 mysql 版本 8 时出现 apt 存储库问题?
- case - 带有 In 子句的 where 子句中的 case 语句
- excel - 防止将新 Excel 工作簿的“文本转换为列”
- javascript - NuxtJs - 如何在以编程方式重定向时修复 nuxtjs 中的“找不到页面”错误?
- json - 编码为 JSON 时如何在 Elixir 中转义单个反斜杠?
- javascript - 如何使用 Javascript 或 Node.js 检查 Windows 操作系统更新状态?
- php - 从数据库中分解数组的正确方法如何使其成为 Codeigniter 下拉列表中的选项