Home > Backend Development > Python Tutorial > 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
Release: 2024-11-02 20:22:30
Original
427 people have browsed it

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>
Copy after login

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>
Copy after login

Output:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template