python __init__.py 在3.4中被证明是无关紧要的?
python __init__.py proved to be irrelevant in 3.4?
我是运行 python 3.4 上的main.py 文件在同一个目录下。
/root 目录不在 python 路径中。它只是脚本正在执行的当前目录。每次测试后删除所有 pycache 文件夹
那么为什么 __init__.py
很重要呢?我认为这是必要的 post:
What is __init__.py for?
If you remove the init.py file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail.
现在,在我看来 __init__.py
只不过是一个 optional 构造函数,我们可以在其中进行内务处理和其他可选的事情,例如指定 "all" 变量等。但不是关键项目。
显示测试结果的图片:
这是怎么回事?
回答
本质上我们不需要 init.py,它的目的是用于遗留和可选的内务处理(2.7 对 3),您可能想做也可能不想做或不需要。但与此同时,它们在更复杂的解析过程中的行为略有不同,如果您正在构建更复杂的东西,也应该考虑到这一点
更多阅读请参考以下链接material
https://www.python.org/dev/peps/pep-0420/#namespace-packages-today
How do I create a namespace package in Python?
What's the difference between a Python module and a Python package?
尽管基础知识在没有 __init__.py
文件的情况下也能正常工作,但它可能令人困惑,但您可能仍应使用它们。如果没有它们,许多外部工具以及标准库中与包相关的函数将无法按预期工作。这里有更多智慧的话(以及误导性的公认答案):.
我是运行 python 3.4 上的main.py 文件在同一个目录下。 /root 目录不在 python 路径中。它只是脚本正在执行的当前目录。每次测试后删除所有 pycache 文件夹
那么为什么 __init__.py
很重要呢?我认为这是必要的 post:
What is __init__.py for?
If you remove the init.py file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail.
现在,在我看来 __init__.py
只不过是一个 optional 构造函数,我们可以在其中进行内务处理和其他可选的事情,例如指定 "all" 变量等。但不是关键项目。
显示测试结果的图片:
这是怎么回事?
回答
本质上我们不需要 init.py,它的目的是用于遗留和可选的内务处理(2.7 对 3),您可能想做也可能不想做或不需要。但与此同时,它们在更复杂的解析过程中的行为略有不同,如果您正在构建更复杂的东西,也应该考虑到这一点
更多阅读请参考以下链接material
https://www.python.org/dev/peps/pep-0420/#namespace-packages-today
How do I create a namespace package in Python?
What's the difference between a Python module and a Python package?
尽管基础知识在没有 __init__.py
文件的情况下也能正常工作,但它可能令人困惑,但您可能仍应使用它们。如果没有它们,许多外部工具以及标准库中与包相关的函数将无法按预期工作。这里有更多智慧的话(以及误导性的公认答案):