What is the key difference between @staticmethod and @classmethod in Python? | A1Lab@MZeeshanM to PythonEnglish • 2 days ago

What is the key difference between @staticmethod and @classmethod in Python?

message-square
0

A @classmethod receives the class itself (cls) as its implicit first argument—allowing it to access or mutate class-level state and construct instances polymorphically in subclasses (return cls(...))—whereas a @staticmethod receives no implicit first argument (self or cls), functioning as an ordinary utility function namespaced inside the class body.

Basic Example

from datetime import date

class Person:
    species = "Homo sapiens"

    def __init__(self, name: str, age: int) -> None:
        self.name = name
        self.age = age

    # 1. `@classmethod`: Receives `cls` — ideal for alternative constructors & subclassing
    @classmethod
    def from_birth_year(cls, name: str, birth_year: int) -> "Person":
        return cls(name, date.today().year - birth_year)

    # 2. `@staticmethod`: Receives NO `self` or `cls` — pure helper namespaced on the class
    @staticmethod
    def is_adult(age: int) -> bool:
        return age >= 18

class Employee(Person):
    pass

# `from_birth_year` called on `Employee` automatically returns an `Employee` instance:
emp = Employee.from_birth_year("Alice", 1995)
print(type(emp).__name__, emp.name, emp.age)
# Output: Employee Alice 31

print(Person.is_adult(emp.age))
# Output: True

Key Details & Edge Cases

  • Inheritance & Polymorphism (cls(...) vs. hardcoded Person(...)):
    • Because a @classmethod dynamically receives whichever class it was invoked on (Employee.from_birth_year(...) passes cls = Employee), calling cls(...) instantiates the subclass, not the base class. If you wrote from_birth_year as a @staticmethod returning Person(...), calling Employee.from_birth_year(...) would erroneously return a plain Person instead of an Employee.
  • Both can be called on either the class (Person.method()) or an instance (emp.method()):
    • Calling emp.from_birth_year(...) still passes type(emp) (Employee) as cls, not emp. Calling emp.is_adult(20) passes only 20 and ignores emp completely.
  • Accessing or modifying class attributes (cls.attr):
    • Use @classmethod whenever a method needs to read or update class-level configuration, registries, or counters (cls._registry.append(...)) without hardcoding the class name—this ensures subclasses with overridden class attributes behave properly.
  • When to use a module-level function instead of @staticmethod:
    • Unlike Java or C#, Python does not require every function to live inside a class. Prefer @staticmethod only when the helper is conceptually tied to the class’s domain API (or when subclasses might override that helper via self.helper() / cls.helper()). Otherwise, a module-level helper function is cleaner and more Pythonic.
  • Combining @classmethod with @property:
    • Chaining @classmethod + @property was briefly supported in Python 3.9–3.10 and deprecated/removed in Python 3.11–3.13 (TypeError: 'classmethod' object is not callable). Use a standard @classmethod getter method (Config.get_default()) or a metaclass @property instead.

Comparison of @classmethod, @staticmethod, and Regular Instance Methods

Feature Instance Method (def fn(self)) @classmethod (def fn(cls)) @staticmethod (def fn())
Implicit First Argument Instance (self) Class (cls) None
Can Read/Modify Instance State (self.x)? Yes No No
Can Read/Modify Class State (cls.x)? Yes (type(self).x) Yes (cls.x) Only by hardcoding class name
Polymorphic Across Subclasses (cls(...))? Yes Yes No (no access to cls)
Primary Use Case Core object behavior operating on instance data. Alternative constructors (from_json, from_dict) and class-state factories/registries. Domain-specific validation or calculation helpers that need neither self nor cls.