[Python] 使用 inspect.getclasstree 秀出類別的繼承關係圖

[Python] 使用 inspect.getclasstree 秀出類別的繼承關係圖

在寫 python 程式時,有時會需要知道某個 class 的繼承關係,

舉例來說,我想知道 IOError 是繼承自哪些父類別的話,

通常會用 __bases__ 屬性來查詢,但是得一個個往上查,相當麻煩:

>>> IOError.__bases__
(<type 'exceptions.EnvironmentError'>,)
>>> EnvironmentError.__bases__
(<type 'exceptions.StandardError'>,)
>>> StandardError.__bases__
(<type 'exceptions.Exception'>,)
>>> Exception.__bases__
(<type 'exceptions.BaseException'>,)
>>> BaseException.__bases__
(<type 'object'>,)
>>> object.__bases__
()

 

今天在網路上找到了一個更方便的方式,就是利用內建的 inspect 模組~

它提供了一個 getmro() 函式,可以把所有的父類別列出來,

而 getclasstree() 函式會把類別以巢狀 list 的方式呈現:

>>> import inspect
>>> inspect.getclasstree(inspect.getmro(IOError))
[(<type 'object'>, ()), [(<type 'exceptions.BaseException'>, (<type 'object'>,)), [(<type 'exceptions.Exception'>, (<type 'exceptions.BaseException'>,)), [(<type 'exceptions.StandardError'>, (<type 'exceptions.Exception'>,)), [(<type 'exceptions.EnvironmentError'>, (<type 'exceptions.StandardError'>,)), [(<type 'exceptions.IOError'>, (<type 'exceptions.EnvironmentError'>,))]]]]]]

 

加上 pprint 的話,階層會更清楚:

>>> from pprint import pprint
>>> pprint(inspect.getclasstree(inspect.getmro(IOError)))
[(<type 'object'>, ()),
[(<type 'exceptions.BaseException'>, (<type 'object'>,)),
[(<type 'exceptions.Exception'>, (<type 'exceptions.BaseException'>,)),
[(<type 'exceptions.StandardError'>, (<type 'exceptions.Exception'>,)),
[(<type 'exceptions.EnvironmentError'>,
(<type 'exceptions.StandardError'>,)),
[(<type 'exceptions.IOError'>,
(<type 'exceptions.EnvironmentError'>,))]]]]]]

 

參考資料:List all base classes in a hierarchy of given class?

 

(本頁面已被瀏覽過 274 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料