python - 从字符串定义变量

标签 python scope

我正在尝试在函数内部定义变量。 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/

相关文章:

python - 如何使用 DOcplex (python) 向模型添加二次约束?

python - 在运行 python 3.8 的机器上用于 python 3.7 的 distutils 和 pygame

python - 为什么Python会尝试提前在多处理中进行一些计算

python - 将两个 numpy 数组中的值与 'if' 进行比较

c++ - 如何引用与 C++ 中的局部变量同名的全局变量?

c++ - 当我为我的简单类数组重载赋值运算符时,我得到了我期望的错误答案

python - 在 PyInstaller 应用程序中启用 Windows 长文件路径支持

C++:使用带有排序函数的完全限定名称 - 行为不一致

oauth - Instagram API : do scopes work with OAuth2 implicit authentication flow?

ruby-on-rails-3 - rails 复杂的多对多查询