是否可以使用 Python 代码创建一个局部变量,只给出变量的名称(一个字符串),以便后续调用 locals() 中的“'xxx'”将返回 True?
这是一个视觉效果:
>>> 'iWantAVariableWithThisName' in locals()
False
>>> junkVar = 'iWantAVariableWithThisName'
>>> (...some magical code...)
>>> 'iWantAVariableWithThisName' in locals()
True
出于什么目的我需要这个诡计完全是另一个话题......
感谢您的帮助。
最佳答案
如果你真的想要这样做,你可以使用exec
:
print 'iWantAVariableWithThisName' in locals()
junkVar = 'iWantAVariableWithThisName'
exec(junkVar + " = 1")
print 'iWantAVariableWithThisName' in locals()
当然,任何人都会告诉你使用 exec 是多么危险和骇人听闻,但是这种“诡计”的任何实现都会如此。
关于python - 是否可以 "dynamically"在 Python 中创建局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8799446/