python 补充:__init__.py 文件的作用

1、新建文件夹时,如果存在 __init__.py 文件,IDE 会自动识别成 module package 

2、python __init__.py  作为包必不可少的一部分,提供了可初始化的配置,可以简化 module package 的导入操作

  2.1  有如下目录结构,使用 tree /F  命令查看(windows)

>tree /F
卷 新加卷 的文件夹 PATH 列表
卷序列号为 00000028 ECD9:68AA
E:.
│  __init__.py
│
├─myPak_one
│  │  demo_1.py
│  │  __init__.py
│  │
│  └─__pycache____init__.cpython-38.pyc
│
├─myPak_three
│      demo_4.py
│
├─myPak_two
│      demo_1.py
│      demo_2.py
│      __init__.py

  2.2  import 导入包时,首先执行 __init__.py 文件的内容:

    1:修改 __init__.py 文件内容

# File  : __init__.py.py
# IDE   : PyCharm

print('Start by opening __init__.py')

    2:命令行模式执行 python

E:personalGitWorkSpacepytest_basic	est_init>python
Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import myPak_two
Start by opening __init__.py

  2.3  __all__变量,将所有需要引用的模块集合在 __all__ 列表中,存在大量模块需要导入时,此方式可以减少代码量(可以在配置 __init__.py 文件时,将需要导入的包通过 from A import B的方式初始化,配合 __all__ 变量使用)

# File  : __init__.py.py
# IDE   : PyCharm

print('Start by opening __init__.py')
__all__ = ['demo_1']
# File  : demo_3.py
# IDE   : PyCharm

# 在 myPak_one.demo_3 中导入 myPak_two 后,会发现 demo_2.py 文件不存在,证明__all__变量生效了
from test_init import myPak_two
print(myPak_two.demo_2.abx())

# >>> AttributeError: module 'test_init.myPak_two' has no attribute 'demo_2'
喜时之言,多失信;怒时之言,多失体
原文地址:https://www.cnblogs.com/xiaohuboke/p/13524109.html