我在 python 教程中看到了这个:
The __init__.py files are required to make Python treat the directories as containing packages;
我在 pycharm 中的目录层次结构是这样的,其中 subdir1 不包含 __init__.py 而 subdir2 包含一个 __init__.py 文件。
首先,我将 Directory 添加到 system.pyth 中。
我分别在hello1.py和hello2.py中写了一个hello函数。
然后我像这样在测试文件中调用 hello func:
# test1.py
from subdir1 import hello1
hello1.hello()
# test2.py
from subdir2 import hello2
hello2.hello()
他们都成功了。似乎 __init__.py 不需要从不同目录导入模块,对吧?
所以,我想知道在什么情况下需要 __init__.py。感谢您的回答!
最佳答案
Python 3.3+ 具有隐式命名空间包,允许您在没有 __init__.py
的情况下创建包。在 Python 2 中,__init__.py
是旧方法并且仍然有效。
Allowing implicit namespace packages means that the requirement to provide an __init__.py file can be dropped completely, and affected portions can be installed into a common directory or split across multiple directories as distributions see fit.
注意:init.py 文件用于将磁盘上的目录标记为 Python 包。
有用的链接:
关于python - 每个 python 包都需要 __init__.py 吗? [自 python 3.3+ 以来的新功能],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47738532/