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

Ivy
Ivy
发布时间:2026-10-13| 6人浏览过
原创

本文介绍如何利用Python内置的dir函数获取类中定义的方法列表。通过示例展示如何结合filter和lambda表达式,筛选出符合特定命名特征的方法,帮助开发者快速定位类接口。

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

在Python中,利用内置函数dir可以获取模块内定义的名称列表。

官方文档对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 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。