global和exec在一起不起作用:解析器的占用问题

初学python,使用3.6版本。

       在做一个小练习的时候,需要在一个局部函数里定义一个全局变量(当然我明白这样做很笨拙而且几乎没有实际意义)。于是写出了类似下面的语句:

def  func():
         a=input('the name of ur var')
         exec('global'+str(a)+'=[]' )
或者这样的语句:

def  func():
         a=input('the name of ur var')
         exec(‘global’+str(a))
         exec('str(a)+'=[]' )

诸如此类……

        这些‘函数’无一例外,在运行并输入a后,什么都没有发生。

        在经历了一段时间的百思不得其解之后,我选择去网上学习,并查阅了python文档。最终我找到了答案:

        在global statement下面的程序员建议里,有如下叙述:

       

Programmer’s note: the global is a directive to the parser. It applies only to code parsed at the same time as theglobal statement. In particular, aglobal statement contained in a string or code object supplied to the built-inexec() function does not affect the code blockcontaining the function call, and code contained in such a string is unaffected byglobal statements in the code containing the function call. The same applies to theeval() andcompile() functions.


        说得已经很明白了吧,再去看了exec()的叙述:

Programmer’s hints: dynamic evaluation of expressions is supported by thebuilt-in functioneval(). The built-in functionsglobals() andlocals() return the current global and local dictionary, respectively,which may be useful to pass around for use byexec.


        说明了二者在解释器的使用上存在一个同时使用的问题(个人理解,欢迎指正),所以不会同时起作用,所以也不会引发错误。

        最后,如果执意想实现这个奇葩的功能,也非常好办。只需要在函数里调用globals()这个字典即可,比如这个程序可以这样写:

       

def  func():
         a=input('the name of ur var')
         globals()[str(a)]=[]

      想要的功能即可完美实现。

      当然,出于程序设计的考虑,如果真的要有这种需求,就是在局部操作中更改位于全局的数据库。那么还是按照常用的做法,定义一个字典,再在局部函数中对这个全局字典进行操作比较好。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值