__all__作用范围
来源:7-9 __init__.py 的用法

云霄9
2018-05-31
老师你好,想请教以下__all__的作用范围。具体问题如下:
folder: Chapter8
folder: t
file: __init__.py:
code: __all__ = ['c1']
file: c1.py:
code:
__all__ = ['a', 'c']
a = "this is a in module t.c1"
b = "this is b in module t.c1"
c = "this is c in module t.c1"
file: c2.py:
code:
f = "this is f in module t.c2"
file: c3.py:
code:
from t import *
print(c1.a)
print(c1.b)
final result:
"this is a in module t.c1"
"this is b in module t.c1"
问题:
使用 from t import * 时,c1.py中的__all__定义的['a', 'c']并没有起作用
如果换成from t.c1 import *时,c1.py中的__all__定义的['a', 'c']起作用
是不是__all__起作用的范围有什么规则?
1回答
-
向也
2018-06-21
我理解 from t import * 是直接去统一导入包下面的所有模块和变量,不存在逐级导入,也就是模块再去执行导变量的过程;所以c1的__all__不生效,c3自然能访问c1的变量,不信打印c2的f试试呢
而form t.c1 imoort * 则指明从c1导变量,all当然生效了
10
相似问题