Python 中 __all__ 的作用(转)

之前看代码每次遇到import *时就会特别蒙,看到这篇文章一下子就弄明白了,原文地址:https://www.cnblogs.com/alamZ/p/6943869.html

 

1.测试文件foo.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
__all__ = ['bar', 'baz']
waz = 5
bar = 10
def baz():
    return 'baz'
2.引入上文件,创建run-foo.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from foo import *
print(bar)
print(baz)
# The following will trigger an exception, as "waz" is not exported by the module
# 下面的代码就会抛出异常,因为 "waz"并没有从模块中导出,因为 __all__ 没有定义
print(waz)

3.运行结果

4.把foo.py的“__all__ = ['bar', 'baz']” 注释,运行正常

它不仅在第一时间展现了模块的内容大纲,而且也更清晰的提供了外部访问接口。

原文地址:https://www.cnblogs.com/luhouxiang/p/8470885.html