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

相关文章

详解Python用三种方式统计词频的方法

三种方法: ①直接使用dict ②使用defaultdict ③使用Counter  ps:`int()`函数默认返回0  ①dict text = "I'm a...

Python实现购物程序思路及代码

要求: 启动程序后,让用户输入工资,然后打印出带有序号的商品列表 用户输入商品序号购买相应的商品,或者输入 ' q ' 退出购买界面 选择商品后,检查余额是否足够,够则直接扣款,不够则提...

解决Python使用列表副本的问题

要使用一个列表的副本,要用切片进行列表复制,这样会形成两个独立的列表。 切记不要将列表赋值给一个列表,因为这样并不能得到两个列表。 1、使用赋值语法创建列表副本的问题 下边就将列表赋值,...

python中urllib模块用法实例详解

本文实例讲述了python中urllib模块用法。分享给大家供大家参考。具体分析如下: 一、问题: 近期公司项目的需求是根据客户提供的api,我们定时去获取数据, 之前的方案是用php收...

对Python生成汉字字库文字,以及转换为文字图片的实例详解

对Python生成汉字字库文字,以及转换为文字图片的实例详解

笔者小白在收集印刷体汉字的深度学习训练集的时候,一开始就遇到的了一个十分棘手的问题,就是如何获取神经网络的训练集数据。通过上网搜素,笔者没有找到可用的现成的可下载的汉字的训练集,于是笔者...