首页 > 技术文章 > Python中__all__的作用

zukang 2021-06-03 19:30 原文

__all__ = [<string>]

它是一个string元素组成的list变量,定义了当你使用 from <module> import * 导入某个模块的时候能导出的符号(这里代表变量,函数,类等)。

其实就是代码保护,限定本模块中只有哪些能被import。

举例:foo.py

__all__ = ['a', 'b']

a = "a"
def b(): return 'b'
c = "c"

  现导入如下:

from foo import *

print a
print b

#The following will trigger an exception, as "c" is not exported by the module
print c

  

推荐阅读