__all__
__all__可用于模块导入时限制,如:
from module import *
此时被导入模块module中
若定义了__all__属性,则只有all内指定的属性、方法、类可被导入
若没定义__all__属性,则模块内的所有将被导入
使用示例
a.py
__all__ = ['test1']
def test1():
print("-----test1-----")
def test2():
print("-----test2-----")
b.py
from a import *
test1() #输出:-----test1-----
test2() #报错,name 'test2' is not defined
注意: __all__ 只影响到了 from <module> import * 这种导入方式
对于如下导入方式并没有影响,仍然可以从外部导入
1) from <module> import <member>
2) import <module>
--------------------------------------------------------------------------------------------------------------------
本文介绍Python中如何使用__all__来控制模块导入时的行为。通过示例代码展示了当使用from module import *的方式导入模块时,__all__的作用及限制。同时说明了其对其他导入方式的影响。
1114

被折叠的 条评论
为什么被折叠?



