当我们创建一个文件时 test1.py
#!/usr/bin/env python3 __arg1 = "lihuanyu01" _arg2 = "lihuanyu02" arg03 = "lihuanyu03" def show(): print("lihuanyu")
但我们使用指令from test1 import *
,将所用的模块都导入进来时候,我们dir( )
查看内置函数
['In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_dh', '_i', '_i1', '_i2', '_ih', '_ii', '_iii', '_oh', 'arg03', 'exit', 'get_ipython', 'quit', 'show']
我们发现不包含__arg1
,_arg2
,这说明只导入了不以下划线开始的所有属性。
当们创建一个package(test)
init.py的程序如下
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 16 21:58:20 2020 @author: lihuanyu """ __arg1 = "lihuanyu01" _arg2 = "lihuanyu02" arg03 = "lihuanyu03" def show(): print("lihuanyu")
但我们使用指令from test import *
,将所用的模块都导入进来时候,我们用dir( )
查看内置函数。
['In', 'Out', '_', '_2', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_dh', '_i', '_i1', '_i2', '_i3', '_i4', '_ih', '_ii', '_iii', '_oh', 'arg03', 'exit', 'get_ipython', 'quit', 'show']
不包含__arg1
,_arg2
,这说明以包的形式导入,也不会将含有下划线的属性导入。
__all__操作
我们在__init__.py
引入__all__ =[""]
,代码如下
""" Created on Mon Nov 16 21:58:20 2020 @author: lihuanyu """ __arg1 = "lihuanyu01" _arg2 = "lihuanyu02" arg03 = "lihuanyu03" __all__ =[""] def show(): print("lihuanyu")
则通过dir()得到的属性如下所示
['In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_dh', '_i', '_i1', '_i2', '_ih', '_ii', '_iii', '_oh', 'exit', 'get_ipython', 'quit']
此时我们定义的__arg1
,_arg2
,arg3
均为含有,这是因为__all__
是空列表,屏蔽了所有属性的导入。
我们在__init__.py
引入__all__ = ["__arg1"]
,代码如下
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 16 21:58:20 2020 @author: lihuanyu """ __all__ = ["__arg1"] __arg1 = "lihuanyu01" _arg2 = "lihuanyu02" arg03 = "lihuanyu03" def show(): print("lihuanyu")
结果为
['In', 'Out', '_', '__', '___', '__arg1', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_dh', '_i', '_i1', '_i2', '_ih', '_ii', '_iii', '_oh', 'exit', 'get_ipython', 'quit']
此时只有__arg1
属性
总结
当模块设有 all 变量时,只能导入该变量指定的成员,未指定的成员是无法导入的。