我是 Python 新手。最近我在读Python Tutorial我有一个关于“导入*”的问题。教程内容如下:
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.
根据我的理解, from sound.effects import * 不应该意味着“导入 sound.effects 下的所有内容”吗? “它只确保包 sound.effects”已导入”是什么意思?有人可以解释一下这一段吗,因为我现在真的很困惑?非常感谢。
最佳答案
What does "it only ensures that the package sound.effects" has been imported" mean?
导入模块意味着执行文件内顶部缩进级别的所有语句。大多数这些语句都是 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的文件中的模块”。
当描述说
and then imports whatever names are defined in the package
它(令人困惑地)对“导入”一词使用了不同的含义。在这种情况下,这意味着包中定义的名称(即 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}
>>>
关于python - 谁能帮忙解释一下Python教程中的这一段吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17539122/