python - 每个 python 包都需要 __init__.py 吗? [自 python 3.3+ 以来的新功能]

标签 python python-3.6

我在 python 教程中看到了这个:

The __init__.py files are required to make Python treat the directories as containing packages;

我在 pycharm 中的目录层次结构是这样的,其中 subdir1 不包含 __init__.py 而 subdir2 包含一个 __init__.py 文件。 enter image description here

首先,我将 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 包。

有用的链接:

  1. Implicit Namespace Packages

关于python - 每个 python 包都需要 __init__.py 吗? [自 python 3.3+ 以来的新功能],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47738532/

相关文章:

python - Pandas/Python 破坏 DataFrame 中的 JSON 数据

c++ - 'PyCObject_Import ("cairo", "CAPI")' C++ call yields segfault, ' import cairo' 在 python 上有效

python - 如何使用 flask 和 html 返回在下拉列表中选择的值列表

Python 循环法

python-3.6 - 带有 `str.__len__(x) == 2` 的单个(重音)字符

python - 函数组合操作的 "functional"包的替代方案是什么?

python - 如何在python中声明一个数组

javascript - 获取类型错误 : 'NoneType' object is not iterable when sending ajax post request django views

python - 使用 *args 时函数参数的类型安全 (mypy)

来自 python 的 redis 在 cli 中显示