__init__.py的用法

在python编译的时候,会在当前目录中自动生成一个 __pycache__的文件夹,这个文件夹对我们开发者来说没什么用处,我们可以隐藏它,那么在vscode中如何隐藏特定的文件呢?

  1. 进入设置:code/setting 或者 快捷键cmd+,

  2. 搜索 files.exclude

  3. 添加 **/__pycache__


├── __init__.py
├── __pycache__
│   ├── c1.cpython-38.pyc
│   └── c2.cpython-38.pyc
├── c1.py
├── c2.py
├── c4.py
└── t
    ├── __pycache__
    │   └── c3.cpython-38.pyc
    └── c3.py

改写c3.py

a = 2
b = 3
c = 4

另一种写法,按需引入

from t.c3 import a,b,c
"""
等价于
from t.c3 import a
from t.c3 import b
from t.c3 import c
"""
print(a)
print(b)
print(c)

来看一个例子

导入包的时候,包下的 __init__.py 会自动运行

在文件夹t下新建一个__init__.py

├── __init__.py
├── __pycache__
│   ├── c1.cpython-38.pyc
│   └── c2.cpython-38.pyc
├── c1.py
├── c2.py
├── c4.py
└── t
    ├── __pycache__
    │   └── c3.cpython-38.pyc
    └── c3.py
    └── __init__.py
a = " this is file __init__.py"

print(a)

c4.py

from t.c3 import a,b,c
print(a)
print(b)
print(c)

run c4.py

 this is file __init__.py
2
3
4

再改写t4.py

import t

run c4.py, 得到

 this is file __init__.py

可以看到__init__.py里面的代码会自动运行,实际编程中,我们会把__init__.py用来初始化包和模块

├── __init__.py
├── __pycache__
│   ├── c1.cpython-38.pyc
│   └── c2.cpython-38.pyc
├── c1.py
├── c2.py
├── c4.py
└── t
    ├── __pycache__
    │   └── c3.cpython-38.pyc
    └── c3.py
    └── c5.py
    └── __init__.py

__init__.py常见用法

  • __all__的用法
  • 批量导入模块:比如下面的代码如果你经常使用 sys,io 就不用在每个模块中引入 sys,io .etc

c3.py

a = 2
b = 3
c = 4
e = 7
f = 8
g = 9
import sys
import io
import datetime

__all__ = ['c5','sys'] # 这里面放的是模块,当在外面使用from t import * 后,即可使用模块名.xx 访问属性和方法

c4.py

from t import *

print(sys.path)
print(c5.e)
print(c3.a) # 由于c3模块没有导出,所以访问的时候报错了
['/Users/scottxiong/Desktop/end/python', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python38.zip', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload', '/Users/scottxiong/Library/Python/3.8/lib/python/site-packages', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages']
7
Traceback (most recent call last):
  File "/Users/scottxiong/Desktop/end/python/c4.py", line 5, in <module>
    print(c3.a)
NameError: name 'c3' is not defined

另一种写法

c4.py

import t

print(t.sys.path)
print(t.c5.e)

results matching ""

    No results matching ""