这是我的项目结构(Python 3.5.1.):
a
├── b.py
└── __init__.py
案例一
文件
b.py为空。文件
__init__.py是:print(b)
如果我们运行import a,输出是:
NameError: name 'b' is not defined
案例2
文件
b.py为空。文件
__init__.py是:import a.b print(b)
如果我们运行import a,输出是:
<module 'a.b' from '/tmp/a/b.py'>
问题
为什么程序在情况 2 中没有失败?
通常如果我们运行import a.b,那么我们只能通过a.b引用它,而不是b。希望有人可以帮助解释案例 2 中的命名空间发生了什么。
请您参考如下方法:
Python 在导入后将模块作为全局变量添加到父包。
因此,当您导入 a.b 时,名称 b 将作为全局变量添加到 a 模块,由 a/创建__init__.py.
来自Python 3 import system documentation :
When a submodule is loaded using any mechanism (e.g. importlib APIs, the import or import-from statements, or built-in
__import__()) a binding is placed in the parent module’s namespace to the submodule object. For example, if packagespamhas a submodulefoo, after importingspam.foo,spamwill have an attributefoowhich is bound to the submodule.
大胆强调我的。请注意,这同样适用于 Python 2,但 Python 3 使该过程更加明确。
