问题
This question already has an answer here:
- Dynamically set local variable [duplicate] 7 answers
Is it possible to create a local variables with Python code, given only the variable's name (a string), so that subsequent calls to "'xxx' in locals()" will return True?
Here's a visual :
>>> 'iWantAVariableWithThisName' in locals()
False
>>> junkVar = 'iWantAVariableWithThisName'
>>> (...some magical code...)
>>> 'iWantAVariableWithThisName' in locals()
True
For what purpose I require this trickery is another topic entirely...
Thanks for the help.
回答1:
If you really want to do this, you could use exec
:
print 'iWantAVariableWithThisName' in locals()
junkVar = 'iWantAVariableWithThisName'
exec(junkVar + " = 1")
print 'iWantAVariableWithThisName' in locals()
Of course, anyone will tell you how dangerous and hackish using exec is, but then so will be any implementation of this "trickery."
回答2:
You can play games and update locals() manually, which will sometimes work, but you shouldn't. It's specifically warned against in the docs. If I had to do this, I'd probably use exec:
>>> 'iWantAVariableWithThisName' in locals()
False
>>> junkVar = 'iWantAVariableWithThisName'
>>> exec(junkVar + '= None')
>>> 'iWantAVariableWithThisName' in locals()
True
>>> print iWantAVariableWithThisName
None
But ninety-three times out of one hundred you really want to use a dictionary instead.
回答3:
No need to use exec, but locals()[string], or vars() or globals() also work.
test1="Inited"
if not "test1" in locals(): locals()["test1"] = "Changed"
if not "test1" in locals(): locals()["test2"] = "Changed"
print " test1= ",test1,"\n test2=",test2
来源:https://stackoverflow.com/questions/8799446/is-it-possible-to-dynamically-create-local-variables-in-python