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

xiaoxiao2021-02-28  55

初学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)]=[]       想要的功能即可完美实现。

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

转载请注明原文地址: https://www.6miu.com/read-80649.html

最新回复(0)