locals().update(dictionary)没有添加所有变量

2024-06-16 10:30:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在使用dictionary对象加载变量,但是值会更新。我错过了什么?在

assert "run_LMM" in all_variables.keys()
locals().update(all_variables)
assert "run_LMM" in locals()

最后一行是我得到一个断言错误。发生什么事?在


Tags: 对象runindictionary错误updateassert断言
1条回答
网友
1楼 · 发布于 2024-06-16 10:30:06

这就是the docs的预期行为:

The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

我想,其中一个原因是在函数编译过程中定义了变量是全局变量还是局部变量,因此:

def func():
    locals()['val'] = 1
    print val

最后一条语句总是从全局变量读取,因为局部变量没有声明。所以,动态添加局部变量的能力会让生活变得更困难。在

相关问题 更多 >