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中的*重复运算符

在python中有个特殊的符号“*”,可以用做数值运算的乘法算子,也是用作对象的重复算子,但在作为重复算子使用时一定要注意 注意的是:*重复出来的各对象具有同一个id,也就是指向在内存...

Python3实现发送邮件和发送短信验证码功能

Python3实现发送邮件和发送短信验证码功能

 Python3实现发送邮件: import smtplib from email.mime.text import MIMEText from email.utils i...

Python使用xlrd模块操作Excel数据导入的方法

本文实例讲述了Python使用xlrd模块操作Excel数据导入的方法。分享给大家供大家参考。具体分析如下: xlrd是一个基于python的可以读取excel文件的产品。和pyExce...

Python中正则表达式的用法实例汇总

正则表达式是Python程序设计中非常实用的功能,本文就常用的正则表达式做一汇总,供大家参考之用。具体如下: 一、字符串替换 1.替换所有匹配的子串 用newstring替换subjec...

Python正则表达式知识汇总

1. 正则表达式语法   1.1 字符与字符类      1 特殊字符:\.^$?+*{}[]()|       以上特殊字符要想使用字面值,必须使用\进行转义 &nb...