from ... import ... 语句如何导入全局变量 [英] How does from ... import ... statement import global variables

查看:41
本文介绍了from ... import ... 语句如何导入全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚它在引擎盖下是如何工作的.我有以下文件:

test.py

x = 20定义 foo():打印 x

test2.py

from test import foo富()

当我在 test2.py 中导入 foo 函数时,它如何解析 x.据我所知,语句 from test import foo 只导入了 foo 函数.

解决方案

函数保留对其模块全局变量的引用.foo 有这样一个引用:

<预><代码>>>>从测试导入 foo>>>foo.__globals__{'x': 20, 'foo':

当你导入某些东西时,Python 会创建一个模块对象;此对象存储在 sys.modules 中,并用作该模块的全局命名空间.import 语句然后将本地"模块中的名称绑定到同一对象或该对象的属性.

函数引用相同的命名空间以从定义它们的地方查找全局变量;它们基本上引用了同一个字典对象:

<预><代码>>>>导入系统>>>foo.__globals__ 是 sys.modules['test'].__dict__真的

I can't figure out how does it works under the hood. I have following files:

test.py

x = 20

def foo():
    print x

test2.py

from test import foo

foo()

When I import the foo function in test2.py how does it resolves x. As far as I know the statement from test import foo imports only the foo function.

解决方案

Functions retain a reference to their module globals. foo has such a reference:

>>> from test import foo
>>> foo.__globals__
{'x': 20, 'foo': <function foo at 0x102f3d410, ...}

What happens is that Python creates a module object when you import something; this object is stored in sys.modules and it serves as the global namespace for that module. The import statement then binds names in your 'local' module to either that same object or to attributes of that object.

Functions reference the same namespace for looking up globals from where they were defined; they essentially reference the same dictionary object:

>>> import sys
>>> foo.__globals__ is sys.modules['test'].__dict__
True

这篇关于from ... import ... 语句如何导入全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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