python 補充--__init__.py 檔案的作用
阿新 • • 發佈:2020-08-18
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:\personal\GitWorkSpace\pytest_basic\test_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'