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 for creating factory methods that build instances of a class using different types of arguments, or for implementing methods related to the class itself rather than any individual object.
Example
Here’s an example of how you can use a class method:
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.
Related Resources
Tutorial
Python's Instance, Class, and Static Methods Demystified
Compare instance methods vs class methods vs static methods in Python, and learn when each one earns its place in your code.
For additional information on related topics, take a look at the following resources:
- OOP Method Types in Python: @classmethod vs @staticmethod vs Instance Methods (Course)
- Providing Multiple Constructors in Your Python Classes (Tutorial)
- Using Multiple Constructors in Your Python Classes (Course)
- Python Classes: The Power of Object-Oriented Programming (Tutorial)
- Class Concepts: Object-Oriented Programming in Python (Course)
- Python's Instance, Class, and Static Methods Demystified (Quiz)
- Inheritance and Internals: Object-Oriented Programming in Python (Course)
- Python Classes - The Power of Object-Oriented Programming (Quiz)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.
By Leodanis Pozo Ramos • Updated Oct. 11, 2026