考虑以下目录结构,
parent
├── __init__.py
├── mod1.py
├── mod2.py
└── mod3.py
文件内容和python版本是,
$ cat __init__.py
from . import mod1
hello = "parent Hello"
$ cat mod1.py
from . import mod2
hello = "parent.mod1 Hello"
$ cat mod2.py
hello = "parent.mod2 hello"
$ cat mod3.py
hello = "parent.mod3 Hello"
$ python3 -V
Python 3.5.2
现在在交互式 session 中我得到以下行为,
>>> import parent
>>> parent.mod1
<module 'parent.mod1' from '/home/codeman/mydata/local/tmp/parent/mod1.py'>
>>> parent.mod2
<module 'parent.mod2' from '/home/codeman/mydata/local/tmp/parent/mod2.py'>
>>> parent.mod3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'parent' has no attribute 'mod3'
当我只在 parent/__int__.py
文件中导入 mod1
时,为什么可以访问 parent.mod2
? (这是一个错误吗?)
据我所知,发生 parent.mod3
的 AttributeError 是因为当使用 importparent 直接导入父级时,只能访问
语法。__init__.py
文件中导入的模块
最佳答案
每当导入模块时,Python 都会创建一个模块对象并将其存储在 sys.modules
中字典。同一模块的后续导入将重用 sys.modules 中的模块对象。此外,每次导入子模块时,该属性都会添加到父模块对象中。
对于给定的 Python 进程,有一个 sys.modules
实例,因此,一般每个 Python 进程的每个模块只有一个实例。这意味着如果您有权访问模块对象,您也可以访问已在当前进程中的任何位置导入的子模块。
在这种特殊情况下,import package
运行package/__init__.py,它导入package.mod1
,它导入package .mod2
。因此,mod1
和 mod2
被添加到“共享”parent
模块对象中,您可以访问它们。
关于Python 3导入异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45344731/