无法访问通过更改函数内部的locals()创建的变量 [英] Can't access variable created by altering locals() inside function
问题描述
在调用以变量名作为参数的函数时,我需要分配一些变量.
I need to assign some variables when calling a funcion with the name of the variable as an argument.
因此,我遍历具有所需名称的元组,并通过 locals()
字典对其进行分配.
Therefore, I loop through a tuple with the desired names, assigning them via the locals()
dict.
它可以工作,但是后来我无法按名称访问它们-即使在函数本身内部.
It works, but then I can't access them by name - even inside the function itself.
def function():
var_names = ("foo","bar","foobar")
for var_name in var_names:
locals()[var_name] = len(var_name)
print foo
投掷:
Traceback (most recent call last):
File "error_test.py", line 8, in <module>
function()
File "error_test.py", line 5, in function
print foo
NameError: global name 'foo' is not defined
使用以下代码,效果很好:
With the following code it works well:
def function():
var_names = ("foo","bar","foobar")
for var_name in var_names:
locals()[var_name] = len(var_name)
print locals()["foo"]
locals()
字典是否仅包含普通的函数变量?为什么不起作用?
Isn't it that the locals()
dict contains just the normal function variables? Why isn't it working?
推荐答案
编写时:
for var_name in var_names:
locals()[var_name] = len(var_name)
您修改 locals()
字典:
作为@ user2357112 在文档中适当链接:>
as @user2357112 aptly linked in 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.
因此修改 locals()
会删除局部变量,因此出现 NameError: global name 'foo' is not defined
错误.
So modifying locals()
deletes the local variables, hence the NameError: global name 'foo' is not defined
error.
这篇关于无法访问通过更改函数内部的locals()创建的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!