Python实现使用dir获取类的方法列表

yipeiwu_com5年前Python基础

使用Python的内置方法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方法,我们可以在一个类的内部,获取当前类的名字满足某些特征的所有方法。

下面是一个例子:

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))

执行:

print A().get_A_X_methods()

输出结果为:

> ['A_X_1', 'A_X_2', 'A_X_3']

以上这篇Python实现使用dir获取类的方法列表就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Pytorch 实现计算分类器准确率(总分类及子分类)

分类器平均准确率计算: correct = torch.zeros(1).squeeze().cuda() total = torch.zeros(1).squeeze().cuda...

使用python制作游戏下载进度条的代码(程序说明见注释)

使用python制作游戏下载进度条的代码(程序说明见注释)

import time # time模块中包含了许多与时间相关的模块,其中通过time()函数可以获取当前的时间。 count = 100 print("开始下载".center(...

python删除过期文件的方法

本文实例讲述了python删除过期文件的方法。分享给大家供大家参考。具体实现方法如下: # remove all jpeg image files of an expired mod...

详解从Django Rest Framework响应中删除空字段

我使用django-rest-framework开发了一个API. 我正在使用ModelSerializer返回模型的数据. models.py class MetaTags(mod...

Python字符串的一些操作方法总结

Python字符串的一些操作方法总结

我们在进行编程学习的时候,不管学习什么编程语言都会用到字符串,对于字符串的一些操作,我们很有必要学的精通一点。 我们在操作字符串的时候用到split用法,主要用来将字符串根据某些特殊要求...