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

yipeiwu_com6年前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设计】。

相关文章

Python迷宫生成和迷宫破解算法实例

Python迷宫生成和迷宫破解算法实例

迷宫生成 1.随机PRIM 思路:先让迷宫中全都是墙,不断从列表(最初只含有一个启始单元格)中选取一个单元格标记为通路,将其周围(上下左右)未访问过的单元格放入列表并标记为已访问,再随机...

python 读取文件并把矩阵转成numpy的两种方法

在当前目录下: 方法1: file = open(‘filename') a =file.read() b =a.split(‘\n')#使用换行 len(b) #统计有多少行...

python针对excel的操作技巧

一. openpyxl读 95%的时间使用的是这个模块,目前excel处理的模块,只有这个还在维护 1、workBook workBook=openpyxl.load_workboo...

python 图片验证码代码分享

复制代码 代码如下: #coding: utf-8 import Image,ImageDraw,ImageFont,os,string,random,ImageFilter def i...

在Python的Django框架中显示对象子集的方法

现在让我们来仔细看看这个 queryset 。 大多数通用视图有一个queryset参数,这个参数告诉视图要显示对象的集合。 举一个简单的例子,我们打算对书籍列表按出版日期排序,最近的排...