Codectionary / Developer documentation / Python

@staticmethod and @classmethod

Regular instance methods automatically receive self, the specific object they were called on. @staticmethod methods receive neither self nor the class - they behave like a plain function that just happens to live inside a class, grouped there for organizational purposes. @classmethod methods receive the class itself (conventionally named cls) instead of an instance, making them useful for alternative constructors that build an instance in a different way.

Syntax

@staticmethod\ndef method(): ...\n\n@classmethod\ndef method(cls): ...

Examples

Static Method

A utility method related to the class that does not need access to instance or class data.

class MathUtils:
    @staticmethod
    def is_even(n):
        return n % 2 == 0

print(MathUtils.is_even(4))   # True, called directly on the class
print(MathUtils.is_even(7))   # False

Class Method

A method that operates on the class itself rather than a specific instance.

class Employee:
    count = 0

    def __init__(self, name):
        self.name = name
        Employee.count += 1

    @classmethod
    def get_employee_count(cls):
        return cls.count

e1 = Employee("John")
e2 = Employee("Zain")
print(Employee.get_employee_count())  # 2

Class Method as an Alternative Constructor

A very common use of @classmethod: providing extra ways to build an instance.

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

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

    def __repr__(self):
        return f"{self.year}-{self.month:02d}-{self.day:02d}"

d1 = Date(2026, 3, 3)
d2 = Date.from_string("2026-07-16")
print(d1, d2)

Best practices

  • Use @staticmethod for helper functions logically related to the class but that need no access to self or cls
  • Use @classmethod for alternative constructors (like from_string) or methods that operate on class-level data
  • Prefer a module-level function instead of a @staticmethod when the logic has no real connection to the class at all
  • Remember @classmethod receives cls (the class), which correctly refers to subclasses too - important when the method is inherited

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading