Python檢視模組(變數 函式 類)方法

2022-09-17 04:03:13 字數 1649 閱讀 6742

通過 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() 函式輸出結果的基礎上,篩選出對我們有用的成員並顯示出來。

除了使用 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() 函式。

Python檢視模組(變數 函式 類)方法

通過 dir 函式,我們可以檢視某指定模組包含的全部成員 包括變數 函式和類 注意這裡所指的全部成員,不僅包含可供我們呼叫的模組成員,還包含所有名稱以雙下劃線 開頭和結尾的成員,而這些 特殊 命名的成員,是為了在本模組中使用的,並不希望被其它檔案呼叫。這裡以匯入 string 模組為例,string...

python 之 函式,類,模組

一 函式 程式中重用 定義函式,def 函式名 函式 示例 usr bin python def myfunction name print this is my first function s name myfunction functionname this is my first funct...

Python 函式,類,模組,異常

def demo print shao f lambda a,b a bdef demo x print shao str x demo 嚶嚶嚶 def demo x 嚶嚶嚶 print shao str x demo demo 12138 def demo x print shao x demo ...