Home >Backend Development >Python Tutorial >How to Obtain a List of Methods within a Python Class?

How to Obtain a List of Methods within a Python Class?

Susan Sarandon
Susan SarandonOriginal
2024-10-29 20:40:02288browse

How to Obtain a List of Methods within a Python Class?

Getting a List of Methods in a Python Class

Iterating through a class's methods or handling its objects differently based on its methods requires retrieving a list of those methods. This article provides two approaches to achieve this.

Using inspect.getmembers()

This function takes a class or instance as its first argument and a predicate function as its second argument. The predicate function filters the returned list based on a specific criterion. To retrieve a list of methods in a class, we can pass inspect.ismethod as the predicate function.

<code class="python">from inspect import getmembers, ismethod

class MyClass:
    def method1(self):
        pass

    def method2(self):
        pass    

# Python 2.x
methods = getmembers(MyClass, ismethod)

# Python 3.x
methods = getmembers(MyClass, isfunction)</code>

The methods variable will contain a list of tuples, each tuple containing the method name and the method object.

Using dir()

The dir() function returns a list of all attributes of an object, including methods. However, it also includes non-method attributes, which may require additional filtering.

<code class="python">methods = [m for m in dir(MyClass) if callable(getattr(MyClass, m))]</code>

The callable() filter checks if an attribute is callable, indicating a method. Keep in mind that this approach may not be as reliable as using inspect.getmembers() because it may include non-method attributes.

The above is the detailed content of How to Obtain a List of Methods within 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