Python包和__init__.py文件

在eclipse中用pydev开发python脚本时,当新建一个package时,系统会自动地生成一个空的__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部分。

本文出自 “青峰” 博客,请务必保留此出处

 

猜你喜欢

转载自lkl.iteye.com/blog/2217714