Python查看模塊(變量、函數、類)方法

查看模塊成員:dir()函數

通過 dir() 函數,我們可以查看某指定模塊包含的全部成員(包括變量、函數和類)。注意這裏所指的全部成員,不僅包含可供我們調用的模塊成員,還包含所有名稱以雙下劃線“__”開頭和結尾的成員,而這些“特殊”命名的成員,是爲了在本模塊中使用的,並不希望被其它文件調用。

這裏以導入 string 模塊爲例,string 模塊包含操作字符串相關的大量方法,下面通過 dir() 函數查看該模塊中包含哪些成員:

import string
print(dir(string))

程序執行結果爲:

['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_re', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace']

可以看到,通過 dir() 函數獲取到的模塊成員,不僅包含供外部文件使用的成員,還包含很多“特殊”(名稱以 2 個下劃線開頭和結束)的成員,列出這些成員,對我們並沒有實際意義。

因此,這裏給讀者推薦一種可以忽略顯示 dir() 函數輸出的特殊成員的方法。仍以 string 模塊爲例:

import string
print([e for e in dir(string) if not e.startswith('_')])

程序執行結果爲:

['Formatter', 'Template', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace']

顯然通過列表推導式,可在 dir() 函數輸出結果的基礎上,篩選出對我們有用的成員並顯示出來。

查看模塊成員:__all__變量

除了使用 dir() 函數之外,還可以使用 __all__ 變量,藉助該變量也可以查看模塊(包)內包含的所有成員。

仍以 string 模塊爲例,舉個例子:

import string
print(string.__all__)

程序執行結果爲:

['ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace', 'Formatter', 'Template']

顯然,和 dir() 函數相比,__all__ 變量在查看指定模塊成員時,它不會顯示模塊中的特殊成員,同時還會根據成員的名稱進行排序顯示。

不過需要注意的是,並非所有的模塊都支持使用 __all__ 變量,因此對於獲取有些模塊的成員,就只能使用 dir() 函數。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章