Python实现使用dir获取类的方法列表
使用Python的内置方法dir,可以范围一个模块中定义的名字的列表。
官方解释是:
Docstring: dir([object])->listofstrings Ifcalledwithoutanargument,returnthenamesinthecurrentscope. Else,returnanalphabetizedlistofnamescomprising(someof)theattributes ofthegivenobject,andofattributesreachablefromit. Iftheobjectsuppliesamethodnamed__dir__,itwillbeused;otherwise thedefaultdir()logicisusedandreturns: foramoduleobject:themodule'sattributes. foraclassobject:itsattributes,andrecursivelytheattributes ofitsbases. foranyotherobject:itsattributes,itsclass'sattributes,and recursivelytheattributesofitsclass'sbaseclasses.
通过dir方法,我们可以在一个类的内部,获取当前类的名字满足某些特征的所有方法。
下面是一个例子:
classA(object): defA_X_1(self): pass defA_X_2(self): pass defA_X_3(self): pass defget_A_X_methods(self): returnfilter(lambdax:x.startswith('A_X')andcallable(getattr(self,x)),dir(self))
执行:
printA().get_A_X_methods()
输出结果为:
>['A_X_1','A_X_2','A_X_3']
以上这篇Python实现使用dir获取类的方法列表就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。