python3.6 中__init__.py对于一个包来说是否是必须的?
在 python tutorial 中,我看到这样一句话:
The __init__.py files are required to make Python treat the directories as containing packages;
我在 pycharm 中像这样设置了文件目录的层次,其中 subdir1
没有 __init__.py
,而 subdir2
有__init__.py
。在 hello1.py
和 hello2.py
中,我都写了一个 hello
函数,然后从位于 subdir3
目录下的两个 test 程序中调用 hello
函数,结果都成功运行了。是不是意味着有没有 __init__.py
作用一样?都可以被位于其他目录下的程序 import?
# test1.py
from subdir1 import hello1
hello1.hello()
# test2.py
from subdir2 import hello2
hello2.hello()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
从Python 3.3开始就不需要了,
PEP 420
相关说明PEP 420链接:https://docs.python.org/3/wha...
参考:https://stackoverflow.com/que...
如果不添加__init__ python不会将其视作包,这个是包的
初始化入口
,当你第一次import
该包时,会运行__init__。该包的__file__属性会指向__init__所在路径。你这里说的没有__init__的是python3的新feature:命名空间包。这么写在python2中是报错的。
你可以看看区别。
必要的, 我觉得还有别的作用, 比如我自己总结过: https://juejin.im/post/5a2cfc...
Python的设计理念是“一切皆对象”。所以,给人的感觉就是 python 包的构造器
__init__.py
,或类的构造函数__init.__()
是可有可无的。但是,包的构造器
__init__.py
或类的构造函数__init.__()
也不是一无是处的,在其中,可有重新定义包或类里的子包,函数、属性的名称,使其按照自己的命名规范对外提供 api 服务等,详情可有自行必应。关于Python包和模块的区别,你可以简单的把包理解为windows的目录。包是模块的特例,典型的说。任何含有__path__ 属性的模块都可以认为是包