這篇文章討論了Python的from <module> import *和from <package> import *,它們怎么執行以及為什么使用這種語法(也許)是一個壞主意。
從一個模塊導入全部
from <module> import * means意味著“我希望能訪問<module>中我有權限訪問的全部名稱”。例如以下代碼something.py:
# something.py public_variable = 42_private_variable = 141 def public_function(): print("I'm a public function! yay!") def _private_function(): print("Ain't nobody accessing me from another module...usually") class PublicClass(object): pass class _WeirdClass(object): pass在Python解釋器中,我們可以執行from something import *,然后看到如下的內容:
>>> from something import *>>> public_variable42>>> _private_variable...NameError: name '_private_variable' is not defined>>> public_function()"I'm a public function! yay!">>> _private_function()...NameError: name '_private_function' is not defined>>> c = PublicClass()>>> c<something.PublicClass object at ...>>>> c = _WeirdClass()...NameError: name '_WeirdClass' is not defined
from something import *從something中導入了除了以_開頭名稱外的其他所有名稱,按照規范,_開始的名稱是私有的所以未被導入。
嗯,不是特別糟!還有什么?
上面沒提到__all__是什么。__all__是一個字符串列表,指定了當from <module> import *被使用時,模塊(或者如后文會提到的包)中的哪些符號會被導出。如果我們不定義__all__(我們在上面的something.py就沒定義),import *默認的導入方式是導入除了下劃線(_)開頭的所有名稱。再說一次,編程慣例上下劃線表示一個符號是私有的,不導入是合理的。讓我們來看看在something.py中定義我們自己的__all__會發生什么。
# something.py __all__ = ['_private_variable', 'PublicClass'] # The rest is the same as before public_variable = 42_private_variable = 141 def public_function(): print("I'm a public function! yay!") def _private_function(): print("Ain't nobody accessing me from another module...usually") class PublicClass(object): pass class _WeirdClass(object): pass現在,我們期望from something import *只會導入_private_variable和PublicClass:
>>> from something import *>>> public_variable42>>> _private_variable...NameError: name '_private_variable' is not defined>>> public_function()"I'm a public function! yay!">>> _private_function()...NameError: name '_private_function' is not defined>>> c = PublicClass()>>> c<something.PublicClass object at ...>>>> c = _WeirdClass()...NameError: name '_WeirdClass' is not defined
新聞熱點
疑難解答