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自动化破解自定义字体混淆信息的方法实例

注意:本示例仅供学习参考~ 混淆原理 出于某种原因,明文信息通过自定义字体进行渲染,达到混淆目的。 举个例子: 网页源码 <p>123</p> 在正常字体的渲染下...

python 并发下载器实现方法示例

本文实例讲述了python 并发下载器实现方法。分享给大家供大家参考,具体如下: 并发下载器 并发下载原理 from gevent import monkey import geve...

OpenCV3.0+Python3.6实现特定颜色的物体追踪

OpenCV3.0+Python3.6实现特定颜色的物体追踪

一、环境 win10、Python3.6、OpenCV3.x;编译器:pycharm5.0.3 二、实现目标 根据需要追踪的物体颜色,设定阈值,在视频中框选出需要追踪的物体。 三、实现步...

使用Django启动命令行及执行脚本的方法

使用django启动命令行和脚本,可以方便的使用django框架做开发,例如,数据库的操作等。 下面分别介绍使用方法。 django shell的启动 启动命令: $/data/py...

浅谈Django+Gunicorn+Nginx部署之路

前言 最近,我已经成功将我的个人网站从 Flask 迁移到 Django 了,最早接触 Django 的时候大概是在 4 年前,我记得那个时候 Django 中的路由配置使用 正则 来...