Python模塊在使用中的兩種導入方法
Python模塊的兩種導入方法。我們在使用的時候需要不斷的學習。其實我們只要是掌握了相關代碼的編寫在實際應用中兩種都有用,你應該知道什么時候使用哪一種方法。
一種方法,import module,你已經在第 2.4 節(jié) “萬物皆對象”看過了。另一種方法完成同樣的事情,但是它與第一種有著細微但重要的區(qū)別。
下面是 from module import 的基本語法:
- from UserDict import UserDict
它與你所熟知的 import module 語法很相似,但是有一個重要的區(qū)別:UserDict 被直接導入到局部名字空間去了,所以它可以直接使用,而不需要加上模塊名的限定。你可以導入獨立的項或使用 from module import * 來導入所有東西。
Python 中的 from module import * 像 Perl 中的 use module ;Python 中的 import module 像 Perl 中的 require module 。
Python 中的 from module import * 像 Java 中的 import module.* ;Python 中的 import module 像 Java 中的 import module 。
- import module vs. from module import
- >>> import types>>> types.FunctionType <type 'function'
>>>> FunctionType Traceback (innermost last): File "
<interactive input>", line 1, in ?NameError: There is no
variable named 'FunctionType'>>> from types import
FunctionType >>> FunctionType <type 'function'>
types 模塊不包含方法,只是表示每種 Python 對象類型的屬性。注意這個屬性必需用模塊名 types 進行限定。FunctionType 本身沒有被定義在當前名字空間中;它只存在于 types 的上下文環(huán)境中。這個語法從 types 模塊中直接將 FunctionType 屬性導入到局部名字空間中。現(xiàn)在 FunctionType 可以直接使用,與 types 無關了。 #t#
什么時候你應該使用 from module import?
如果你要經常訪問模塊的屬性和方法,且不想一遍又一遍地敲入模塊名,使用 from module import。如果你想要有選擇地導入某些屬性和方法,而不想要其它的,使用 from module import。如果模塊包含的屬性和方法與你的某個模塊同名,你必須使用 import module 來避免名字沖突。除了這些情況,剩下的只是風格問題了,你會看到用兩種方式編寫的 Python 代碼。
盡量少用 from module import * ,因為判定一個特殊的函數(shù)或屬性是從哪來的有些困難,并且會造成調試和重構都更困難。