「它只確保package sound.effects」已被導入「是什麼意思?
導入模塊意味着在文件內部的頂部縮進級別執行所有語句。這些語句中的大多數將是def或class語句,它們創建一個函數或類並給它一個名稱;但是如果有其他語句,他們也會被執行。
[email protected]:/tmp$ cat sound/effects/utils.py
mystring = "hello world"
def myfunc():
print mystring
myfunc()
[email protected]:/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/__init__.py
sounds/effects/utils.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}
>>>
您是否瞭解包的基礎知識(與普通模塊相反)? – abarnert