在源码中我们时常看到在某模块中写入__all__=['a','b'] 它是用来限制模块导入的变量或方法的,别的模块只能从该模块中导入__all__列表中的变量或方法,仅在 from module import * 中可以用
此时被导入模块若定义了__all__属性(注意__all__是一个列表),则只有__all__内指定的属性、方法、类可被导入。
若没定义,则导入模块内的所有公有属性,方法和类 。
注意:在import module 或 from module import a 中都不适用
定义一个all.py模块
__all__=['x','y','test'] x=2 y=3 z=4 def test(): print('test')
在测试文件test1中导入all.py
from all import * print('x:',x) print('y:',y) print('z:',z) test()
结果:
Traceback (most recent call last): x: 2 File "C:/Users/stickerzhang/PycharmProjects/untitled3/算法/text/test1.py", line 11, in <module> print('z:',z) y: 3 NameError: name 'z' is not defined
浙公网安备 33010602011771号