加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python exec中的范围

发布时间:2020-12-20 13:28:49 所属栏目:Python 来源:网络整理
导读:当在exec中定义变量/函数时,它似乎转到locals()而不是globals(),我怎么能改变这种行为?只有在将全局和本地词典传递给exec时才会发生这种情况. 例: exec("""a = 2def foo(): print afoo()""") in {},{} 当你尝试这个: NameError: global name 'a' is not d
当在exec中定义变量/函数时,它似乎转到locals()而不是globals(),我怎么能改变这种行为?只有在将全局和本地词典传递给exec时才会发生这种情况.

例:

exec("""
a = 2

def foo():
    print a

foo()""") in {},{}

当你尝试这个:

NameError: global name 'a' is not defined

解决方法

乍一看对我来说也很奇怪.但是有了更多输出我找到了原因:

>>> g,l = {},{}
>>> print id(g),id(l)
12311984 12310688
>>>
>>> exec '''
... a = 2
... print 'a' in globals(),'a' in locals(),id(globals()),id(locals())
... def f():
...     print 'a' in globals(),id(locals())
... f()
... ''' in g,l
False True 12311984 12310688
False False 12311984 12311264

如http://effbot.org/pyfaq/what-are-the-rules-for-local-and-global-variables-in-python.htm所述:

In Python,variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function’s body,it’s assumed to be a local. If a variable is ever assigned a new value inside the function,the variable is implicitly local,and you need to explicitly declare it as global.

所以一个解决方案是对全局变量和本地变量使用相同的dict:

>>> l = {}
>>> exec '''
... a = 2
... def f():
...     print a
... f()
... ''' in l,l
2

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读