2013-07-09 22 views
1

我是Python新手。最近我在閱讀Python Tutorial,我有一個關於「導入*」的問題。以下是本教程的內容:任何人都可以幫助詳細說明Python教程中的這一段嗎?

如果__all__未定義,則來自sound.effects的語句import *不會將包中的所有子模塊導入當前名稱空間;它只確保包sound.effects已被導入(可能在__init__.py中運行任何初始化代碼),然後導入包中定義的任何名稱。這包括__init__.py定義的任何名稱(以及明確加載的子模塊)。

從我的理解,應該從sound.effects不導入*平均 「進口所有下sound.effects」?什麼是「只保證包裝sound.effects」已導入」呢?有人可以給出一個解釋這一段,因爲我現在真的混淆?非常感謝。

+0

您是否瞭解包的基礎知識(與普通模塊相反)? – abarnert

回答

0
import file 

    v = file.Class(...) 

是你有什麼如果你正常導入它,但是'從文件導入' *意味着你可以使用文件中的所有內容而不用關鍵字,而不是'*',你可以指定特定的類等等......

2

「它只確保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__.pysounds/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} 

和以前一樣,myfuncmystring創建,現在他們在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} 
>>> 
0

簡述:

從我的理解,不應該from sound.effects import *的意思是「導入所有sound.effects」?

不,它應該表示import sound.effects,然後使其所有成員都可以無限制地使用。

換句話說,它是關於成員sound.effects,而不是其下的任何模塊或包。

如果sound.effects是一個包,子模塊或子包sound.effects.foo不會自動一個構件的sound.effects。而且,如果它不是成員,它將不會在您的模塊中可用。

那麼,這個「不一定」的資格是什麼?那麼,一旦你import sound.effects.foo,它成爲sound.effects的成員。因此,如果您(或其他人 - 比如soundsound.effects)完成了import,那麼sound.effects.foo複製到您的模塊from sound.effects import *

而這正是在這最後一句括號位是所有關於:

這包括__init__.py定義的任何名稱(和子模塊明確加載)。

相關問題