Can anyone help elaborate on this paragraph in Python tutorial?
我是Python的新手。最近我正在阅读Python教程,我有一个关于"import*"的问题。本教程的内容如下:
If __all__ is not defined, the statement from sound.effects import * does not import all submodules from the package sound.effects into the current namespace; it only ensures that the package sound.effects has been imported (possibly running any initialization code in __init__.py) and then imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by __init__.py.
据我所知,sound.effects import*不应该是"import all under sound.effects"?"它只确保包的声音。效果"是什么意思?我现在真的很困惑,有人能解释一下这段话吗?谢谢。
What does"it only ensures that the package sound.effects" has been imported" mean?
导入一个模块意味着在文件的顶部缩进级别执行所有语句。这些语句中的大多数都是def或class语句,它们创建一个函数或类并给它一个名称;但是如果有其他语句,它们也将被执行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | james@Brindle:/tmp$ cat sound/effects/utils.py mystring ="hello world" def myfunc(): print mystring myfunc() james@Brindle:/tmp$ python Python 2.7.5 (default, Jun 14 2013, 22:12:26) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.60)] on darwin Type"help","copyright","credits" or"license" for more information. >>> import sound.effects.utils hello world >>> dir(sound.effects.utils) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'myfunc', 'mystring'] >>> |
在本例中,您可以看到导入模块sound.effects.utils定义了模块内的名称"mystring"和"myfunc",以及对文件最后一行的"myfunc"的调用。
"导入包sound.effects"是指"导入(即执行)名为sound/effects/init.py的文件中的模块"。
当描述说
and then imports whatever names are defined in the package
它对"import"这个词使用了不同的含义(令人困惑)。在这种情况下,它意味着包中定义的名称(即in it.py中定义的名称)将被复制到包的命名空间中。
如果我们将
1 2 3 4 5 6 | >>> import sound.effects hello world >>> dir(sound.effects) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'myfunc', 'mystring'] >>> locals() {'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', 'sound': <module 'sound' from 'sound/__init__.pyc'>, '__doc__': None, '__package__': None} |
和以前一样,创建了
1 2 3 4 5 6 7 | >>> locals() {'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None} >>> from sound.effects import * hello world >>> locals() {'myfunc': <function myfunc at 0x109eb29b0>, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'mystring': 'hello world', '__name__': '__main__', '__doc__': None} >>> |
简要地:
From my understanding, shouldn't
from sound.effects import * mean"import all under sound.effects"?
不,它应该是指
换句话说,它是关于
如果
那么,"不一定"的条件是什么呢?好吧,一旦你的
这就是最后一句话的附加语:
This includes any names defined (and submodules explicitly loaded) by
__init__.py .
1 2 3 | import file v = file.Class(...) |
如果您正常导入,则必须执行此操作,但"从文件导入"*意味着您可以使用文件的所有内容而不使用关键字。您可以指定特定的类等,而不是"*"。