python version : 2.7.10
问题:在引用一个自己写的module时,报import error,原因是因为在要引的py文件所在文件夹中没有 __init__.py 文件,那么__init__.py 文件有什么用呢?
The __init__.py
files are required to make Python treat the directories as containing packages; 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. In the simplest case, __init__.py
can just be an empty file, but it can also execute initialization code for the package or set the __all__
variable, described later.(引自 https://docs.python.org/3/tutorial/modules.html#packages)
这样做是为了防止带有常用名称的目录, 例如字符串, 以防止无意中隐藏在模块搜索路径上稍后出现的有效模块。 在最简单的情况下, __init__.py可以只是一个空文件, 但它也可以执行包的初始化代码或设置后面描述的所有变量。(翻译自彩云小译网页版)
对上面那段话的理解:
如果你创建了一个string.py 文件,但是在它所在的文件夹中没有__init__.py 文件,则import string module时,不会被import成你写的string.py
The file __init__.py
was required under Python 2.X and is still required under Python 2.7.12 (I tested it) but it is no longer required from (allegedly) Python 3.3 onwards, and is not required under Python 3.4.3
更多请看:https://stackoverflow.com/questions/448271/what-is-init-py-for