gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:29:18 30 4
gpt4 key购买 nike

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

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 - locals().update(dictionary) 不会添加所有变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24197720/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com