Python實(shí)現(xiàn)使用dir獲取類的方法列表
使用Python的內(nèi)置方法dir,可以范圍一個(gè)模塊中定義的名字的列表。
官方解釋是:
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.
通過(guò)dir方法,我們可以在一個(gè)類的內(nèi)部,獲取當(dāng)前類的名字滿足某些特征的所有方法。
下面是一個(gè)例子:
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()
輸出結(jié)果為:
> ['A_X_1', 'A_X_2', 'A_X_3']
以上這篇Python實(shí)現(xiàn)使用dir獲取類的方法列表就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Pandas數(shù)據(jù)分析固定時(shí)間點(diǎn)和時(shí)間差
這篇文章主要介紹了Pandas數(shù)據(jù)分析固定時(shí)間點(diǎn)和時(shí)間差,文章未日澳主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-08-08
Python學(xué)習(xí)之while 循環(huán)語(yǔ)句
這篇文章主要給大家介紹了關(guān)于Python中while循環(huán)語(yǔ)句的相關(guān)資料,使用while循環(huán)語(yǔ)句可以解決程序中需要重復(fù)執(zhí)行的操作,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2021-10-10
python kmeans聚類簡(jiǎn)單介紹和實(shí)現(xiàn)代碼
這篇文章主要為大家詳細(xì)介紹了python kmeans聚類簡(jiǎn)單介紹和實(shí)現(xiàn)代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-02-02
Python中不可錯(cuò)過(guò)的五個(gè)超有用函數(shù)
在本文中,我們用代碼詳細(xì)說(shuō)明了Python中超實(shí)用的5個(gè)函數(shù)的重要作用,這些函數(shù)雖然簡(jiǎn)單,但卻是Python中功能最強(qiáng)大的函數(shù),下面一起來(lái)看看文章的詳細(xì)介紹吧,希望對(duì)你的學(xué)習(xí)有所幫助2022-01-01
python語(yǔ)法學(xué)習(xí)print中f-string用法示例
這篇文章主要為大家介紹了python語(yǔ)法學(xué)習(xí)print中f-string用法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
一篇文章帶你深入學(xué)習(xí)Python函數(shù)
這篇文章主要帶大家深入學(xué)習(xí)Python函數(shù),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助2022-01-01

