导入到

2024-04-26 06:35:39 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的项目结构(Python3.5.1.):

a
├── b.py
└── __init__.py

案例1

  • 文件b.py为空。

  • 文件__init__.py是:

    print(b)
    

如果运行import a,则输出为:

^{3}$

案例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来引用它,而不是{}。希望有人能帮助解释案例2中的名称空间发生了什么。在


Tags: 文件项目frompyimport程序名称init
2条回答

Python在导入后将模块作为全局变量添加到父包中。在

因此,当您导入a.b时,名称b作为一个全局添加到由a/__init__.py创建的a模块中。在

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 package spam has a submodule foo, after importing spam.foo, spam will have an attribute foo which is bound to the submodule.

大胆强调我的。请注意,这同样适用于python2,但是python3使该过程更加明确。在

import语句将模块带入作用域。您导入了b,因此它就是一个模块对象。在

阅读^{}的文档:

The basic import statement (no from clause) is executed in two steps:

  • find a module, loading and initializing it if necessary
  • define a name or names in the local namespace for the scope where the import statement occurs.

在第一种情况下,您没有导入b。在

相关问题 更多 >