在eclipse中用pydev开发python脚本时,当新建一个package时,系统会自动地生成一个空的__init__.py文件。如果把这个文件删掉,那么你会发现包图标自动变为文件夹图标。这是怎么回事呢?
原来在python模块的每一个包中,都必须存在一个__init__.py文件(这个文件定义了包的属性和方法)然后是一些模块文件和子目录,假如子目录中也有 __init__.py 那么它就是这个包的子包了。当你将一个包作为模块导入(比如从 xml 导入 dom )的时候,实际上导入了它的 __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.
有关__all__ 变量的用法,请参考帮助系统中的6.4.1. Importing * From a Package部分。