【发布时间】:2022-01-23 12:31:18
【问题描述】:
我想从 dict 中获取函数工作的变量。
简单示例
>>> def func(atrs):
... for k,v in atrs.items():
... exec(k + '=v')
...
... # do smth here with vars
...
... print(locals()) # lets see that 'a' exists
... print(a) # lets use 'a'
在我使用这个函数后,我得到了错误。
>>> func({'a':1, 'b':5})
{'atrs': {'a': 1, 'b': 5}, 'k': 'b', 'v': 5, 'a': 1, 'b': 5}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in func
NameError: name 'a' is not defined
但我们可以看到“a”存在于已定义的变量中。 我做错了什么?
我看到了,如果我们不使用函数,它就可以工作。 Convert dictionary entries into variables
但我需要使用函数。
【问题讨论】:
标签: python function dictionary nameerror