python脚本下面的 __init__.py 有什么作用?

python脚本下面的 __init__.py 有什么作用?,第1张

The __init__.py files are required to make Python treat the directories as containing packagesthis 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.\x0d\x0a\x0d\x0a在文件夹中包含一个__init__.py,Python就会把文件夹当作一个package,里面的py文件就能搏银够在外面被import了。\x0d\x0a例如文件夹结构是:\x0d\x0asound/局谨 Top-level package\x0d\x0a __init__.py Initialize the sound package\x0d\x0a formats/ Subpackage for file format conversions\x0d\x0a __init__.py\x0d\x0a wavread.py\x0d\x0a wavwrite.py\x0d\x0a aiffread.py\x0d\x0a aiffwrite.py\x0d\x0a auread.py\x0d\x0a auwrite.py\x0d\x0a ...\x0d\x0a effects/ Subpackage for sound effects\x0d\x0a __init__.py\x0d\x0a echo.py\x0d\x0a surround.py\x0d\x0a reverse.py\x0d\x0a ...\x0d\x0a filters/ Subpackage for filters\x0d\x0a __init__.py\x0d\x0a equalizer.py\x0d\x0a vocoder.py\x0d\x0a karaoke.py\x0d\x0a\x0d\x0a外桐银基部就可以import sound.effects.echo来使用,sound文件夹和effects文件夹都被处理成package了。

pycharm创建普通的directory和package时都是在硬盘上建弊迹立一个文件夹。

但是建package时会在这个文件夹中自掘族动地生成一个空的__init__.py文件。

python的一个包是一个带有特殊文件

__init__.py

的目录。__init__.py

文件定义了包的属性和方法。其实它可以什么也不定义;可以只是一个空租散并文件,但是必须存在。如果

__init__.py

不存在,这个目录就仅仅是一个目录,而不是一个包,它就不能被导入或者包含其它的模块和嵌套包。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/12120450.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-21
下一篇 2023-05-21

发表评论

登录后才能评论

评论列表(0条)

保存