Python
Programming
Methods
Classes
Tutorial

How do I get list of methods in a Python class?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Python provides several ways to list the methods of a class: dir() returns all attributes and methods (including inherited ones), inspect.getmembers() with inspect.ismethod or inspect.isfunction filters for callable methods, and vars() returns only attributes defined directly on the class (not inherited). For practical use, inspect.getmembers(cls, predicate=inspect.isfunction) is the most reliable approach for listing user-defined methods.

Method 1: dir()

dir() returns all attribute names (methods, properties, dunder methods, inherited attributes):

python
1class Animal:
2    def __init__(self, name):
3        self.name = name
4
5    def speak(self):
6        return "..."
7
8    def eat(self, food):
9        return f"{self.name} eats {food}"
10
11print(dir(Animal))
12# ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__',
13#  '__eq__', '__format__', '__ge__', ..., 'eat', 'speak']

Filtering dir() for User-Defined Methods

python
1# Exclude dunder methods
2methods = [m for m in dir(Animal) if not m.startswith('_')]
3print(methods)  # ['eat', 'speak']
4
5# Only callable attributes
6methods = [m for m in dir(Animal)
7           if callable(getattr(Animal, m)) and not m.startswith('_')]
8print(methods)  # ['eat', 'speak']

Method 2: inspect.getmembers()

The inspect module provides filtered access to class members:

python
1import inspect
2
3class Calculator:
4    pi = 3.14159
5
6    def add(self, a, b):
7        return a + b
8
9    def multiply(self, a, b):
10        return a * b
11
12    @staticmethod
13    def square(x):
14        return x ** 2
15
16    @classmethod
17    def create(cls):
18        return cls()
19
20# Get all functions (includes instance methods, static, class methods)
21methods = inspect.getmembers(Calculator, predicate=inspect.isfunction)
22print(methods)
23# [('add', <function>), ('multiply', <function>), ('square', <function>)]
24
25# Get class methods
26class_methods = inspect.getmembers(Calculator, predicate=inspect.ismethod)
27print(class_methods)
28# [('create', <bound method>)]

inspect.isfunction returns functions defined with def (including @staticmethod). inspect.ismethod returns bound methods (like @classmethod when inspecting the class).

Method 3: vars()

vars() returns the class's own __dict__, which contains only attributes defined directly in the class (not inherited):

python
1class Base:
2    def base_method(self):
3        pass
4
5class Child(Base):
6    def child_method(self):
7        pass
8
9# vars only shows Child's own attributes
10print(vars(Child).keys())
11# dict_keys(['__module__', '__qualname__', 'child_method', '__doc__'])
12
13# dir shows inherited methods too
14print([m for m in dir(Child) if not m.startswith('_')])
15# ['base_method', 'child_method']

Filtering vars() for Methods

python
1class MyClass:
2    class_var = 42
3
4    def method_a(self):
5        pass
6
7    def method_b(self):
8        pass
9
10methods = {name: val for name, val in vars(MyClass).items()
11           if callable(val) and not name.startswith('_')}
12print(list(methods.keys()))  # ['method_a', 'method_b']

Method 4: type.dict

Equivalent to vars() but works on any type:

python
1# List methods of a built-in type
2list_methods = [m for m in type(list).__dict__ if not m.startswith('_')]
3print(list_methods)
4# ['append', 'clear', 'copy', 'count', 'extend', 'index',
5#  'insert', 'pop', 'remove', 'reverse', 'sort']

Getting Method Signatures

python
1import inspect
2
3class UserService:
4    def create_user(self, name: str, email: str, age: int = 0) -> dict:
5        """Create a new user."""
6        return {"name": name, "email": email, "age": age}
7
8    def delete_user(self, user_id: int) -> bool:
9        """Delete a user by ID."""
10        return True
11
12for name, method in inspect.getmembers(UserService, predicate=inspect.isfunction):
13    sig = inspect.signature(method)
14    doc = inspect.getdoc(method) or "No docstring"
15    print(f"{name}{sig}")
16    print(f"  {doc}")
17    print()
18
19# create_user(self, name: str, email: str, age: int = 0) -> dict
20#   Create a new user.
21#
22# delete_user(self, user_id: int) -> bool
23#   Delete a user by ID.

Listing Methods on an Instance

python
1class Dog:
2    def bark(self):
3        return "Woof!"
4
5    def fetch(self, item):
6        return f"Fetching {item}"
7
8dog = Dog()
9
10# Instance methods
11methods = inspect.getmembers(dog, predicate=inspect.ismethod)
12print([(name, m) for name, m in methods if not name.startswith('_')])
13# [('bark', <bound method>), ('fetch', <bound method>)]
14
15# Check if a specific method exists
16print(hasattr(dog, 'bark'))    # True
17print(callable(getattr(dog, 'bark', None)))  # True

Note: inspect.ismethod returns True for bound methods on instances, while inspect.isfunction returns True for unbound functions on classes.

Comparing Approaches

MethodInheritedDunderPropertiesUse Case
dir(cls)YesYesYesQuick overview
inspect.getmembers(cls, isfunction)YesYesNoFiltered list of methods
vars(cls)NoYesYesOnly directly defined
cls.__dict__NoYesYesSame as vars()

Common Pitfalls

  • dir() includes inherited methods and dunder methods: dir() returns everything — __init__, __str__, inherited methods, properties, and class variables. Always filter the result to get only the methods you care about.
  • Confusing isfunction and ismethod in inspect: On a class, user-defined methods show up as functions (isfunction). On an instance, they are bound methods (ismethod). The predicate you need depends on whether you inspect the class or an instance.
  • vars() misses inherited methods: vars(Child) only shows attributes defined in Child, not those inherited from Base. Use dir() or inspect.getmembers() if you need the complete method list including inherited methods.
  • Properties appearing as methods: @property descriptors are not callable — they appear in dir() but not with inspect.isfunction. Filtering with callable(getattr(cls, name)) incorrectly includes properties because they are accessible.
  • Dynamic methods not appearing: Methods added at runtime with setattr() appear in dir() and vars() on the instance but not on the class. Inspect the specific instance if methods may have been added dynamically.

Summary

  • Use dir(cls) for a quick list of all attributes, then filter with callable() and not m.startswith('_')
  • Use inspect.getmembers(cls, inspect.isfunction) for a clean list of defined methods
  • Use vars(cls) to see only methods defined directly on the class, excluding inherited ones
  • Use inspect.signature() to get method parameters and type annotations
  • isfunction works on classes, ismethod works on instances — choose based on what you are inspecting

Course illustration
Course illustration

All Rights Reserved.