这篇文章讨论了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
新闻热点
疑难解答