Python 中 __all__ 的作用


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.運行結果

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

它不僅在第一時間展現了模塊的內容大綱,而且也更清晰的提供了外部訪問接口。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM