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!