Python 中 all 的用法
all__是针对模块公开接口的一种约定, 定义了__all,其他文件在使用from xxx import *倒入该文件时,只会导入__all__列出的成员
例子
test1.py
def func1():
pass
test2.py
__all__=['func2']
def func2():
pass
def func3():
pass
test3.py
from test2 import *
结果在test3.py中只有func1和func2可以被成功引用
定义__all__需要注意的地方
- __all__需要定义为list的形式
- 不能动态生成,比如列表解析式,所以需要以字面的形式写出来
- 按照PEP8风格,__all__应该写在所有import下面,函数和变量的上面
参考:https://zhuanlan.zhihu.com/p/54274339