是否有可能“动态"地解决问题.在Python中创建局部变量? [英] Is it possible to "dynamically" create local variables in Python?

查看:110
本文介绍了是否有可能“动态"地解决问题.在Python中创建局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以仅使用变量名称(字符串)使用Python代码创建局部变量,以便随后对locals()中的"xxx"的调用将返回True?

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?

这是视觉效果:

>>> 'iWantAVariableWithThisName' in locals()
False
>>> junkVar = 'iWantAVariableWithThisName'
>>> (...some magical code...)
>>> 'iWantAVariableWithThisName' in locals()
True

出于什么目的 我要求这种骗术完全是另一个话题...

For what purpose I require this trickery is another topic entirely...

感谢您的帮助.

推荐答案

如果您真的要这么做,可以使用exec:

If you really want to do this, you could use exec:

print 'iWantAVariableWithThisName' in locals()
junkVar = 'iWantAVariableWithThisName'
exec(junkVar + " = 1")
print 'iWantAVariableWithThisName' in locals()

当然,任何人都会告诉您使用exec有多么危险和骇人听闻,但是这种骗子"的任何实现也会如此.

Of course, anyone will tell you how dangerous and hackish using exec is, but then so will be any implementation of this "trickery."

这篇关于是否有可能“动态"地解决问题.在Python中创建局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆