Mit*_*lad 8 python memory variables local instantiation
是否可以使用Python代码创建局部变量,只给出变量的名称(字符串),以便后续调用locals()中的"'xxx'"将返回True?
这是一个视觉:
>>> 'iWantAVariableWithThisName' in locals()
False
>>> junkVar = 'iWantAVariableWithThisName'
>>> (...some magical code...)
>>> 'iWantAVariableWithThisName' in locals()
True
Run Code Online (Sandbox Code Playgroud)
出于什么目的,我需要这个技巧完全是另一个话题......
谢谢您的帮助.
如果你真的想这样做,你可以使用exec:
print 'iWantAVariableWithThisName' in locals()
junkVar = 'iWantAVariableWithThisName'
exec(junkVar + " = 1")
print 'iWantAVariableWithThisName' in locals()
Run Code Online (Sandbox Code Playgroud)
当然,任何人都会告诉你使用exec是多么危险和恶意,但那么这个"技巧"的实现也是如此.
您可以手动玩游戏和更新本地人(),这有时会有效,但您不应该这样做.它在文档中特别警告.如果我不得不这样做,我可能会使用exec:
>>> 'iWantAVariableWithThisName' in locals()
False
>>> junkVar = 'iWantAVariableWithThisName'
>>> exec(junkVar + '= None')
>>> 'iWantAVariableWithThisName' in locals()
True
>>> print iWantAVariableWithThisName
None
Run Code Online (Sandbox Code Playgroud)
但是,在百分之九十三中你真的想要使用字典.
| 归档时间: |
|
| 查看次数: |
8164 次 |
| 最近记录: |