python包中__init__.py的作用

时间:2023-03-08 22:38:26

1、__init__.py定义包的属性和方法

  一般为空文件,但是必须存在,没有__init__.py表明他所在的目录只是目录不是包

2、导入包的时候使用

  例如有一个test目录,test下有xx1.py,xx2.py,__init__.py三个文件

    | test

    | | __init__.py

    | | xx1.py

    | | xx2.py

  则test可以当作包被导入,导入test下所有的文件

  from test import *

  导入的实际是__init__.py中变量__all__,即__all__ = ['xx1','xx2']

3、__init__.py添加库

  例如在__init__.py中编辑如下内容: 

 import re
import os

  则__all__ = [‘re’,‘os’]

4、__init__.py中添加其他内容

  新建一个test目录,test目录下创建__init__.py和test_import.py连个文件

  __init__.py内容如下:

 print('hello wuya')

  test_import.py内容如下:

 import test

  运行test_import.py,结果如下:

  python包中__init__.py的作用