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

作者:肖哥shelwin 时间:2023-01-04 12:18:44 

使用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']

来源:https://blog.csdn.net/zjuxsl/article/details/77104441

标签:Python,dir,方法列表
0
投稿

猜你喜欢

  • Python基于SMTP发送邮件的方法

    2021-07-17 23:42:46
  • Python生成随机数组的方法小结

    2023-10-09 08:19:41
  • 简明 Python 基础学习教程

    2023-01-05 13:02:05
  • python数据分析之单因素分析线性拟合及地理编码

    2021-02-09 06:46:20
  • Python 实现使用dict 创建二维数据、DataFrame

    2021-09-29 16:49:43
  • OpenCV实现图像平滑处理的方法汇总

    2023-07-12 14:44:33
  • mysql通配符的具体使用

    2024-01-22 18:43:16
  • 关于Django框架的关系模型序列化和一对多关系中的序列化解析

    2023-01-15 00:52:53
  • 如何使用Python对Excel表格进行拼接合并

    2021-03-15 18:01:54
  • 通过实例解析Python return运行原理

    2021-08-11 18:31:31
  • Vue3中简单实现动态添加路由

    2023-07-02 16:58:45
  • Python+django实现文件下载

    2022-03-10 15:54:16
  • Highcharts+NodeJS搭建数据可视化平台示例

    2024-05-02 17:38:38
  • python和shell监控linux服务器的详细代码

    2021-11-09 06:23:22
  • PyQt5每天必学之创建窗口居中效果

    2022-02-16 19:03:49
  • pycharm2022.2远程连接服务器调试代码实现

    2022-11-17 12:12:48
  • 用javascript实现的仿Flash广告图片轮换效果

    2024-04-19 09:59:29
  • 如何使数据库的ID字段自动加1?

    2010-06-03 10:47:00
  • 解决Pycharm调用Turtle时 窗口一闪而过的问题

    2023-05-06 14:46:29
  • 对Python3之进程池与回调函数的实例详解

    2022-07-30 13:07:01
  • asp之家 网络编程 m.aspxhome.com