Home  >  Article  >  Backend Development  >  How to Retrieve a List of Methods in a Python Class?

How to Retrieve a List of Methods in a Python Class?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-02 20:22:30345browse

How to Retrieve a List of Methods in a Python Class?

Retrieving a List of Methods in a Python Class

Overview

Retrieving a list of methods in a Python class allows for flexible object manipulation based on available methods.

Solution

To obtain a list of methods in a class, utilize the inspect module's getmembers function:

<code class="python">import inspect

methods_list = inspect.getmembers(Class, predicate=inspect.ismethod)</code>

where Class represents the target class.

Python 2 vs. Python 3

Note that getmembers returns different results depending on the Python version:

Python 2: Returns a list of tuples: [(method_name, unbound_method_object), ...]

Python 3: Returns a list of method objects: [unbound_method_object, ...]

Parameters

The getmembers function can take the following parameters:

  • predicate: A function to filter the members returned. Only members that pass the predicate are included in the result.
  • instance: An instance of the class to inspect. If not provided, class methods are inspected.

Example

To list the methods of the OptionParser class from optparse:

<code class="python">from optparse import OptionParser
import inspect

print(inspect.getmembers(OptionParser, predicate=inspect.ismethod))</code>

Output:

[('__init__', <unbound method OptionParser.__init__>),
 ('add_option', <unbound method OptionParser.add_option>),
 ('add_option_group', <unbound method OptionParser.add_option_group>),
 ...]

The above is the detailed content of How to Retrieve a List of Methods in a Python Class?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn