1.测试文件foo.py

# -*- coding: utf-8 -*-
# import sys
# reload(sys)
# sys.setdefaultencoding('gbk')

__all__ = ['bar', 'baz']

waz = 5
bar = 10
def baz(): return 'baz'

2.引入上文件,创建run-foo.py

# -*- coding: utf-8 -*-
# import sys
# reload(sys)
# sys.setdefaultencoding('gbk')

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__ 的作用

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

 

相关文章:

  • 2021-09-25
  • 2023-02-10
  • 2021-12-06
  • 2021-12-03
  • 2021-09-22
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-22
  • 2022-12-23
  • 2021-09-11
  • 2021-10-09
相关资源
相似解决方案