Python實現(xiàn)使用dir獲取類的方法列表
更新時間:2019年12月24日 14:37:17 作者:肖哥shelwin
今天小編就為大家分享一篇Python實現(xiàn)使用dir獲取類的方法列表,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
使用Python的內(nèi)置方法dir,可以范圍一個模塊中定義的名字的列表。
官方解釋是:
Docstring: dir([object]) -> list of strings If called without an argument, return the names in the current scope. Else, return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it. If the object supplies a method named __dir__, it will be used; otherwise the default dir() logic is used and returns: for a module object: the module's attributes. for a class object: its attributes, and recursively the attributes of its bases. for any other object: its attributes, its class's attributes, and recursively the attributes of its class's base classes.
通過dir方法,我們可以在一個類的內(nèi)部,獲取當前類的名字滿足某些特征的所有方法。
下面是一個例子:
class A(object): def A_X_1(self): pass def A_X_2(self): pass def A_X_3(self): pass def get_A_X_methods(self): return filter(lambda x: x.startswith('A_X') and callable(getattr(self,x)), dir(self))
執(zhí)行:
print A().get_A_X_methods()
輸出結果為:
> ['A_X_1', 'A_X_2', 'A_X_3']
以上這篇Python實現(xiàn)使用dir獲取類的方法列表就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
python kmeans聚類簡單介紹和實現(xiàn)代碼
這篇文章主要為大家詳細介紹了python kmeans聚類簡單介紹和實現(xiàn)代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-02-02