“它只确保包sound.effects”已经被导入是什么意思?
导入模块意味着在文件内的最高缩进级别执行所有语句。这些语句中的大多数将是 def 或 class 语句,它们创建一个函数或类并为其命名;但如果有其他语句,它们也会被执行。
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的文件中的模块”。
当描述说
然后导入包中定义的任何名称
它(令人困惑地)对“导入”一词使用了不同的含义。在这种情况下,这意味着包中定义的名称(即 init.py 中定义的名称)被复制到包的命名空间中。
如果我们将之前的 sounds/effects/utils.py 重命名为 sounds/effects/__init__.py,会发生以下情况:
>>> 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}
和以前一样,myfunc 和 mystring 已创建,现在它们位于 sounds.effects 命名空间中。
from x import y 语法将事物加载到本地命名空间而不是它们自己的命名空间,因此如果我们从 import sound.effects 切换到 from sound.effects import *,这些名称将被加载到本地命名空间:
>>> 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}
>>>