python vars name报错,Python vars()全局名称错误

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 "", line 1, in

File "", 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

>>>

Edit:

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 "", line 1, in

File "", line 7, in ness

KeyError: 'p'

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.

Thanks much for the assistance.

解决方案

There is way to do it with exec

>>> def ness():

... pie='yum'

... exec pie+"=4"

... print vars()[pie]

... print yum

...

>>>

>>> ness()

4

4

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

>>>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值