python __init__.py file

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值