Python包和__init__.py文件

简介:

 在eclipse中用pydev开发python脚本时,当新建一个package时,系统会自动地生成一个空的__init__.py文件。如果把这个文件删掉,那么你会发现包图标自动变为文件夹图标。这是怎么回事呢?

 

        原来在python模块的每一个包中,都必须存在一个__init__.py文件(这个文件定义了包的属性和方法)然后是一些模块文件和子目录,假如子目录中也有 __init__.py 那么它就是这个包的子包了。当你将一个包作为模块导入(比如从 xml 导入 dom )的时候,实际上导入了它的 __init__.py 文件。

       

         一个包是一个带有特殊文件__init__.py 的目录。__init__.py 文件定义了包的属性和方法。其实它可以什么也不定义;可以只是一个空文件,但是必须存在。如果 __init__.py 不存在,这个目录就仅仅是一个目录,而不是一个包,它就不能被导入或者包含其它的模块和嵌套包。

 

        在python根目录下的帮助文件.chm中是这样描述的:

 

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.

有关__all__ 变量的用法,请参考帮助系统中的6.4.1. Importing * From a Package部分。











本文转自朱先忠老师51CTO博客,原文链接: http://blog.51cto.com/zhuxianzhong/1606428,如需转载请自行联系原作者






相关文章
|
Python
Python 的其他主题:Python 中的 `__init__.py` 文件有什么作用?
Python 的其他主题:Python 中的 `__init__.py` 文件有什么作用?
245 1
|
Python
Python 基础知识:Python 中的 `__init__` 和 `__new__` 方法有什么区别?
Python 基础知识:Python 中的 `__init__` 和 `__new__` 方法有什么区别?
189 1
|
设计模式 存储 Python
【从零学习python 】46. Python中的__new__和__init__方法解析及单例设计模式
【从零学习python 】46. Python中的__new__和__init__方法解析及单例设计模式
140 0
|
机器学习/深度学习 算法 Python
【Python】已完美解决:机器学习填补数值型缺失值时报错)TypeError: init() got an unexpected keyword argument ‘axis’,
【Python】已完美解决:机器学习填补数值型缺失值时报错)TypeError: init() got an unexpected keyword argument ‘axis’,
276 1
|
Web App开发 测试技术 API
【Python】已解决:TypeError: *init*() got an unexpected keyword argument ‘firefox_options’
【Python】已解决:TypeError: *init*() got an unexpected keyword argument ‘firefox_options’
374 0
|
机器学习/深度学习 Python
【Python】已解决TypeError: init() got an unexpected keyword argument ‘threshold’
【Python】已解决TypeError: init() got an unexpected keyword argument ‘threshold’
998 0
|
Python
【Python】已解决:TypeError: *init*() missing 1 required positional argument: ‘scheme’
【Python】已解决:TypeError: *init*() missing 1 required positional argument: ‘scheme’
698 0
|
Python
解释Python中的`__init__`和`__new__`方法的区别。
解释Python中的`__init__`和`__new__`方法的区别。
197 3
|
算法 开发者 Python
【Python 基础扫盲 】self参数、__init__方法和.__str__方法的用处和区别?
【Python 基础扫盲 】self参数、__init__方法和.__str__方法的用处和区别?
673 0
|
Python
Python中__new__和__init__的区别与联系
Python中__new__和__init__的区别与联系
243 0

推荐镜像

更多
下一篇
oss云网关配置