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:
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
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.
For additional information on related topics, take a look at the following resources:
- Providing Multiple Constructors in Your Python Classes (Tutorial)
- Python Classes: The Power of Object-Oriented Programming (Tutorial)
- OOP Method Types in Python: @classmethod vs @staticmethod vs Instance Methods (Course)
- Python's Instance, Class, and Static Methods Demystified (Quiz)
- Using Multiple Constructors in Your Python Classes (Course)
- Class Concepts: Object-Oriented Programming in Python (Course)
- Inheritance and Internals: Object-Oriented Programming in Python (Course)
- Python Classes - The Power of Object-Oriented Programming (Quiz)