Python 中 __all__ 的作用(转)

时间:2022-08-09 08:25:51

之前看代码每次遇到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.运行结果

Python 中 __all__ 的作用(转)

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

Python 中 __all__ 的作用(转)

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