How do I enumerate functions of a Python class?

Python provides several ways to enumerate (list) the functions and methods of a class. The most common approach uses the inspect module to examine class members and filter for callable methods.

Using inspect.getmembers()

The inspect.getmembers() function returns all members of a class. Use inspect.isfunction or inspect.ismethod as a predicate to filter only functions ?

import inspect

class SampleClass:
    def __init__(self):
        self.x = 10
    
    def method_one(self):
        return "First method"
    
    def method_two(self):
        return "Second method"

# Get all methods using inspect
methods = inspect.getmembers(SampleClass, predicate=inspect.isfunction)
print("Class methods:")
for name, method in methods:
    print(f"  {name}: {method}")
Class methods:
  __init__: <function SampleClass.__init__ at 0x...>
  method_one: <function SampleClass.method_one at 0x...>
  method_two: <function SampleClass.method_two at 0x...>

Using dir() Function

The dir() function lists all attributes of a class. Filter callable attributes using callable() ?

class SampleClass:
    def __init__(self):
        self.x = 10
    
    def method_one(self):
        return "First method"
    
    def method_two(self):
        return "Second method"

# Get callable attributes using dir()
all_attributes = dir(SampleClass)
methods = [attr for attr in all_attributes if callable(getattr(SampleClass, attr))]

print("Callable methods:")
for method in methods:
    if not method.startswith('_'):  # Exclude private methods
        print(f"  {method}")
Callable methods:
  method_one
  method_two

Getting Only User-Defined Methods

To exclude built-in methods like __init__, filter out methods starting with underscores ?

import inspect

class SampleClass:
    def __init__(self):
        self.x = 10
    
    def method_one(self):
        return "First method"
    
    def method_two(self):
        return "Second method"

# Get only user-defined methods
methods = inspect.getmembers(SampleClass, predicate=inspect.isfunction)
user_methods = [(name, method) for name, method in methods if not name.startswith('_')]

print("User-defined methods:")
for name, method in user_methods:
    print(f"  {name}")
User-defined methods:
  method_one
  method_two

Comparison

Method Returns Best For
inspect.getmembers() Name-object tuples Getting method objects
dir() + callable() Attribute names Simple name listing
vars() Dictionary Instance attributes

Conclusion

Use inspect.getmembers() with inspect.isfunction for comprehensive method enumeration. Use dir() for simple attribute listing. Filter with underscore checks to exclude built-in methods.

Updated on: 2026-03-24T19:49:47+05:30

274 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements