python 3.x __init__.py文件作用

__init__.py作用

  • 在一个文件夹下如果有__init__.py文件,说明该文件是一个python包.
  • 在实际开发项目中,__init__.py文件是用来做包和模块的初始化.

当一个python包被其他python文件导入引用时,其包下的__init__.py文件首先被自动执行

demo_init包下__init__.py文件

__init__.py

5 ---------------------------------------------------
6 
7 a = "This is a __init__.py file"
8 
9 print(a)
demo1.py

3 # 导入demo_init包,测试是否先自动执行该包下的__init__.py文件
4 import demo_init
5 
6 
7 输出结果:
8 
9 This is a __init__.py file

 

当一个python文件导入引用某一个包下模块的变量时,改包下的__init__.py文件也是先自动执行

demo_init包下__init__.py文件

__init__.py

5 ---------------------------------------------------
6 
7 a = "This is a __init__.py file"
8 
9 print(a)
demo_test.py
 
3 __all__ = ["a","c"]
4 
5 a = 1
6 b = 2
7 c = 3
demo1.py

 3 from demo_init.demo_test import a,c
 4 
 5 print(a)
 6 print(c)
 7 
 8 输出结果:
 9 
10 This is a __init__.py file
11 1
12 3

 

 在__init__.py文件中,使用__all__来筛选哪些模块需要导入

 

demo_test.py

3 __all__ = ["a","c"]
4 
5 a = 1
6 b = 2
7 c = 3
demo2.py
 
3 d = "hello"
4 e = "python"
5 f = "jayden"
demo_init包下__init__.py文件

__init__.py
 
------------------------------------------
 
 7 __all__ = ["demo2"]
 8 
 9 a = "This is a __init__.py file"
10 print(a)
demo1.py

 3 from demo_init import *
 4 
 5 print(demo2.d)
 6 print(demo2.e)
 7 print(demo2.f)
 8 
 9 print(demo_test.a)
10 
11 输出结果:
12 
13 This is a __init__.py file
14 hello
15 python
16 jayden
17 
18 Traceback (most recent call last):
19   File "demo1.py", line 7, in <module>
20     print(demo_test.a)
21 NameError: name 'demo_test' is not defined

 

当一个文件夹下多个python文件都需要导入相同的python内置标准库或者三方库,那么每一个python文件下都要import大量的包很麻烦.

  • 解决办法:将所有需要使用的python内置标准库以及三方库的导包语句放到__init__.py文件中.这样其他文件夹下的python文件使用大量的库时,直接import包即可,然后(包名.库名.方法名or变量名)

 

__init__.py


4 """
5 将所有需要使用的python内置标准库以及三方库的导包语句放到__init__.py文件中
6 """
7 import sys,datetime,io
 1 demo1.py
 2 
 3 """
 4 直接导包即可
 5 """
 6 import demo_init
 7 
 8 # 包名.库名.方法名or变量名
 9 print(demo_init.sys.path)
10 
11 输出结果:
12 ['f:\\C\\AnacondaProject\\demo', 'D:\\python3\\python36.zip', 'D:\\python3\\DLLs', 'D:\\python3\\lib', 'D:\\python3', 'D:\\python3\\lib\\site-packages']

 

********

 

posted on 2018-06-19 10:05  jaydenjune  阅读(52)  评论(0)    收藏  举报

导航