在Python中可以“动态”创建局部变量吗?
有没有办法用Python代码创建一个局部变量,只用变量的名字(一个字符串),这样后面调用"'xxx' in locals()"时会返回True?
这里有个示意图:
>>> 'iWantAVariableWithThisName' in locals()
False
>>> junkVar = 'iWantAVariableWithThisName'
>>> (...some magical code...)
>>> 'iWantAVariableWithThisName' in locals()
True
至于我为什么需要这种技巧,那是另一个话题了...
谢谢大家的帮助。
3 个回答
-2
其实不需要用exec这个东西,你可以用locals()[string]、vars()或者globals()来实现同样的效果。
test1="Inited"
if not "test1" in locals(): locals()["test1"] = "Changed"
if not "test1" in locals(): locals()["test2"] = "Changed"
print " test1= ",test1,"\n test2=",test2
5
你可以手动玩游戏并更新 locals(),这有时候是可以的,但不推荐这么做。文档里特别警告过不要这样。如果我非得这么做,我可能会用 exec:
>>> 'iWantAVariableWithThisName' in locals()
False
>>> junkVar = 'iWantAVariableWithThisName'
>>> exec(junkVar + '= None')
>>> 'iWantAVariableWithThisName' in locals()
True
>>> print iWantAVariableWithThisName
None
不过,百分之九十三的情况下,你其实更想用字典来处理。
9
如果你真的想这么做,可以使用exec
:
print 'iWantAVariableWithThisName' in locals()
junkVar = 'iWantAVariableWithThisName'
exec(junkVar + " = 1")
print 'iWantAVariableWithThisName' in locals()
当然,任何人都会告诉你使用exec是多么危险和像黑客一样的做法,但任何实现这种“花招”的方法也都是一样的。