python之locals().update(dictionary) 不会添加所有变量

thcjp 阅读:74 2024-05-29 10:23:45 评论:0

我一直在使用字典对象加载变量,但值得到了更新。我在这里错过了什么?

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

最后一行是我得到一个断言错误。怎么回事?

请您参考如下方法:

这是预期的行为,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 

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


标签:Python
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号