这位大佬已经写得很好了:
https://blog.csdn.net/chuan_day/article/details/79694319
Python中一个py文件就是一个模块,__all__
变量是一个特殊的变量,可以在py文件中,也可以在包的__init__.py
中出现。
1、在普通模块中使用时,表示一个模块中允许哪些属性可以被导入到别的模块中,
如:全局变量、函数和类等。如下,test1.py和main.py
# 文件 test1.py
__all__=["test"]
def test():
print('----test-----')
def test1():
print('----test1----')
# 文件 main.py
from test1 import *
def main():
test()
#test1()
main()
两个文件在同一个目录下。
此时执行python main.py时结果如下:
但是如果放开main.py的注释后,如下:
2、在包下的__init__.py
中
sound/effects/__init__.py
中添加 __all__ = ["echo", "surround", "reverse"]
那么就会在from sound.effects import *
时,包含上面三个模块。
当__init__.py
为空时,只是导入这个包,并非导入模块。
__init__.py
中可以执行一些初始化内容,比如:
from . import test1
导入当前目录下的test1模块
from .. import test
导入上一层目录下的test模块
因为导入包时会首先执行下__init__.py
这个文件