class method

In Python, a class method is a method that belongs to its containing class rather than to any specific instance of the class.

You can define this type of method using the @classmethod decorator. It should take the class itself as its first argument, conventionally named cls.

Class methods can access and modify class state that applies across all instances of the class. They’re useful to create factory methods that build instances of a class using different types of arguments or to implement methods related to the class itself rather than any individual object.

Example

Here’s an example of how you can use a class method:

Python pizzas.py
class Pizza:
    def __init__(self, ingredients):
        self.ingredients = ingredients

    @classmethod
    def margherita(cls):
        return cls(["mozzarella", "tomatoes"])

    def __str__(self):
        return f"Pizza with {' and '.join(self.ingredients)}"

# Usage
print(Pizza.margherita())  # Output: Pizza with mozzarella and tomatoes

In this example, .margherita() is a class method that lets you quickly prepare a Margherita pizza. Note that the first argument of class methods is the class itself.

Tutorial

Python's Instance, Class, and Static Methods Demystified

In this tutorial, you'll compare Python's instance methods, class methods, and static methods. You'll gain an understanding of when and how to use each method type to write clear and maintainable object-oriented code.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated April 10, 2025 • Reviewed by Leodanis Pozo Ramos