__main__ 和 python 中的范围 [英] __main__ and scoping in python

查看:36
本文介绍了__main__ 和 python 中的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不知何故,我对以下行为感到惊讶:

I was somehow surprised by the following behavior:

def main():
    print "%s" % foo

if __name__ == "__main__":
    foo = "bar"
    main()

即模块函数可以访问 __main__ 中的封闭变量.对此有何解释?

i.e. a module function has access to enclosing variables in the __main__. What's the explanation for it?

推荐答案

当前模块全局范围内的变量在模块中的任何地方都可见——这个规则也适用于 __main__ 模块.

Variables in the current modules global scope are visible everywhere in the module -- this rule also holds for the __main__ module.

来自 Guido 的教程:

在执行过程中的任何时候,至少有三个嵌套的作用域可以直接访问其命名空间:

At any time during execution, there are at least three nested scopes whose namespaces are directly accessible:

  • 首先搜索的最里面的范围包含本地名称
  • 任何封闭函数的范围,从最近的开始搜索封闭作用域,包含非本地名称,但也包含非全局名称
  • 倒数第二个范围包含当前模块的全局名称
  • 最外面的范围(最后搜索)是包含内置名称的命名空间

这篇关于__main__ 和 python 中的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆