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:

Python 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

Python 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:

Python 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:

Python 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.

Tutorial

Python's Instance, Class, and Static Methods Demystified

This tutorial helps demystify what's behind class, static, and instance methods in Python.

intermediate python

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


By Leodanis Pozo Ramos • Updated Nov. 14, 2024 • Reviewed by Dan Bader