classmethod()
The built-in classmethod()
function is a decorator that transforms a method into a class method. A class method receives the class itself as its first argument, enabling it to access or modify class-level data rather than instance data. This functionality is particularly useful for creating multiple constructors, which allow for different ways to instantiate the class:
margherita.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
classmethod() Syntax
@classmethod
def method(cls, *args, **kwargs):
...
Arguments
Argument | Description |
---|---|
method |
A method to be converted into a class method |
Return Value
- Returns a class method object that can be called on both the class and its instances.
classmethod() Examples
As an alternative constructor:
point.py
class ThreeDPoint:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
@classmethod
def from_sequence(cls, sequence):
return cls(*sequence)
def __repr__(self):
return f"ThreeDPoint(x={self.x}, y={self.y}, z={self.z})"
# Usage
print(
ThreeDPoint.from_sequence((4, 8, 16))
) # Output: ThreeDPoint(x=4, y=8, z=16)
classmethod() Common Use Cases
The most common use cases for the @classmethod
include:
- Creating multiple constructors for flexibility in instantiation
- Implementing factory methods to encapsulate complex object creation logic
- Modifying class-level attributes that apply to all instances
classmethod() Real-World Example
A common real-world application of @classmethod
is to create factory methods that return pre-configured instances of a class. For example, a Pizza
class might have class methods for creating specific types of pizzas:
pizzas.py
class Pizza:
def __init__(self, ingredients):
self.ingredients = ingredients
@classmethod
def margherita(cls):
return cls(["mozzarella", "tomatoes"])
@classmethod
def prosciutto(cls):
return cls(["mozzarella", "tomatoes", "ham"])
def __str__(self):
return f"Pizza with {' and '.join(self.ingredients)}"
# Usage
print(
Pizza.margherita()
) # Output: Pizza with mozzarella and tomatoes
print(
Pizza.prosciutto()
) # Output: Pizza with mozzarella and tomatoes and ham
This approach simplifies the creation of Pizza
objects by providing predefined configurations.
Related Resources
Tutorial
Python's Instance, Class, and Static Methods Demystified
This tutorial helps demystify what's behind class, static, and instance methods in Python.
For additional information on related topics, take a look at the following resources:
- Providing Multiple Constructors in Your Python Classes (Tutorial)
- Object-Oriented Programming (OOP) in Python (Tutorial)
- Python Classes: The Power of Object-Oriented Programming (Tutorial)
- OOP Method Types in Python: @classmethod vs @staticmethod vs Instance Methods (Course)
- Using Multiple Constructors in Your Python Classes (Course)
- Intro to Object-Oriented Programming (OOP) in Python (Course)
- Object-Oriented Programming (OOP) in Python (Quiz)
- 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)