Python vars()全局名称错误 [英] Python vars() global name error
问题描述
我在理解以下功能出了什么问题时遇到了麻烦:
I'm having a bit of trouble understanding what's going wrong with the following function:
def ness():
pie='yum'
vars()[pie]=4
print vars()[pie]
print yum
所以当我跑步时,我会得到以下结果:
So When I run that I get this result:
>>> ness()
4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in ness
NameError: global name 'yum' is not defined
如果我不将其编写为函数,而只需一次在命令行中将其键入即可,就像这样:
If I don't write it as a function and just type it in on the command line one line at a time it works fine, like so:
>>> pie='yum'
>>> vars()[pie]=4
>>> print vars()[pie]
4
>>> print yum
4
>>>
假设我想让事情变得比这复杂一些,而不是将yum设置为一个值并打印该值,而是定义了一些函数,并希望根据一些输入来调用其中之一:
Suppose I wanted to make things a bit more complicated than this and instead of setting yum to a value and printing that value, I define some functions, and want to call one of them based on some input:
def ness(choo):
dic={}
dessert=()
dnum=[10,100]
desserts='pie'
dic[dessert]=str(desserts[bisect(dnum,choo)])
vars()[dic[dessert]]()
def p():
print 'ummmm ummm'
def i():
print 'hooo aaaaa'
def e():
print 'woooo'
所以当我打电话给我时,我得到一个关键错误:
So when I call ness I get a key error:
>>> ness(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in ness
KeyError: 'p'
现在我知道我可以使用一些elif语句来做类似的事情,但是我想知道这是否也可以工作,以及是否使用像这样的bisect会更有效(比如我是否需要检查1000个choo值)比起使用Elifs.
Now I know I can do things like this with some elif statements, but I'm wondering if this would work too, and if using bisect like this would be more efficient (say if i need to check 1000 values of choo) than using elifs.
非常感谢您的帮助.
推荐答案
可以通过exec来做到这一点
There is way to do it with exec
>>> def ness():
... pie='yum'
... exec pie+"=4"
... print vars()[pie]
... print yum
...
>>>
>>> ness()
4
4
但是,与其这样做,不如使用一个新的dict更好,更安全
But Instead of doing that, using a new dict is better and safe
>>> def ness():
... dic={}
... pie='yum'
... dic[pie]=4
... print dic[pie]
... print dic['yum']
...
>>> ness()
4
4
>>>
这篇关于Python vars()全局名称错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!