問題描述
我在 python/Lib 源代碼中看到了很多,但我不知道它是干什么用的.
I've seen it a lot in python/Lib source code but I don't know what it is for.
我認為它用于限制模塊的可訪問成員.所以只有 __all__
處的元素會在 dir(module)
時出現.
I thought it was used to limit accessible members of of a module. So only the elements at __all__
will show up when dir(module)
.
我做了一個小例子,發現它沒有按預期工作.
I did a little example and saw it was not working as I expected.
那么... python __all__
模塊級變量是干什么用的?
So... What's the python __all__
module level variable for?
推薦答案
它有兩個目的:
任何閱讀源代碼的人都會知道公開的公共 API 是什么.它不會阻止他們在私有聲明中四處尋找,但確實提供了一個很好的警告.
Anybody who reads the source will know what the exposed public API is. It doesn't prevent them from poking around in private declarations, but does provide a good warning not to.
使用 from mod import *
時,只會導入 __all__
中列出的名稱.在我看來,這并不重要,因為導入所有內容真的是個壞主意.
When using from mod import *
, only names listed in __all__
will be imported. This is not as important, in my opinion, because importing everything is a really bad idea.
這篇關于python __all__ 模塊級變量有什么用?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!