What is the reason python needs __init__.py for packages?
我知道python需要
但是,在python文档中,这一行让我很困惑,
This is done to prevent directories with a common name, such as
string, from unintentionally hiding valid modules that occur later on
the module search path.
如图所示:https://docs.python.org/2/tutorial/modules.html包
有人能解释一下吗?
文档对此非常清楚-您的项目结构可能如下所示:
1 2 3 4 5 6 | app - common - init.py - resources - string - src |
如果python将目录隐式地视为包,则"string"目录可能会出现与python内置的字符串模块(https://docs.python.org/2/library/string.html)名称冲突的情况。这意味着当调用
this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.
假设您有一个为学校工作的目录,其中一些涉及到Python。你有一个数学目录,你称之为数学。您还编写了一个python模块,所以顶层目录"school"已经添加到python路径中,所以您可以在任何地方使用它。
1 2 3 4 5 6 7 8 | School/ math/ hw1.txt integrate.py MyPythonModule/ __init__.py someClass.py someFunc.py |
当您稍后使用python并搜索mypythonmodule时,python将打开
然后它看到了
如果您有一个名为