Python Class Method vs Static Method

In Python object-oriented programming, both class methods and static methods are methods that are bound to a class rather than an instance of that class. However, they differ fundamentally in how they interact with class and instance state. This guide breaks down the core distinctions between the @classmethod and @staticmethod decorators, their technical behaviors, and the specific scenarios where each should be used.

The Core Difference

The primary distinction lies in what parameters are passed to the method when it is called:


What Is a Class Method?

A class method is defined using the @classmethod decorator. Because it receives the class object (cls) automatically, it can inspect or modify class attributes that apply across all instances.

Key Characteristics

Common Use Case: Factory Methods

Class methods are most frequently used to create alternative constructors that process data before returning an instance of the class.

class Date:
    def __init__(self, day, month, year):
        self.day = day
        self.month = month
        self.year = year

    @classmethod
    def from_string(cls, date_string):
        day, month, year = map(int, date_string.split("-"))
        return cls(day, month, year)

# Creating an instance using the alternative constructor
date = Date.from_string("25-12-2024")

What Is a Static Method?

A static method is defined using the @staticmethod decorator. It does not know about the class or the instance from which it was called, receiving only the explicit arguments passed to it.

Key Characteristics

Common Use Case: Utility or Helper Functions

Static methods are ideal for logic that is self-contained and related to the class conceptually, but does not need any data from the class or its instances.

class TemperatureConverter:
    @staticmethod
    def celsius_to_fahrenheit(celsius):
        return (celsius * 9/5) + 32

# Calling the static method directly on the class
temp_f = TemperatureConverter.celsius_to_fahrenheit(100)

Summary Comparison

Feature Class Method (@classmethod) Static Method (@staticmethod)
Decorator @classmethod @staticmethod
First Argument Implicit class reference (cls) None
Access to Class State Yes, via cls No
Access to Instance State No No
Primary Purpose Factory methods, modifying class-level data Independent helper and utility functions

When to Use Which