我正在尝试在函数内部定义变量。 vars() 显示变量已创建,但给我 NameError: exception。我做错了什么?
def a(str1):
vars() [str1] = 1
print vars()
print b
a('b')
输出:
{'str1': 'b', 'b': 1}
异常(exception):
NameError: global name 'b' is not defined
最佳答案
您正在调用未定义的行为。来自documentation of vars()
:
Note The returned dictionary should not be modified: the effects on the corresponding symbol table are undefined.
其他答案给出了可能的解决方案。
关于python - 从字符串定义变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3257672/