Understanding `@staticmethod` vs `@classmethod` in Python
Python provides @staticmethod and @classmethod for methods that do not operate on one specific instance. They look similar at first, but they receive different context and solve different problems.
@staticmethod
A static method receives no implicit self or cls argument:
class Temperature:
@staticmethod
def celsius_to_fahrenheit(value):
return value * 9 / 5 + 32
print(Temperature.celsius_to_fahrenheit(20))Use a static method when a function logically belongs in the class namespace but does not need instance or class state.
@classmethod
A class method receives the class as its first argument, conventionally named cls:
class User:
def __init__(self, name):
self.name = name
@classmethod
def anonymous(cls):
return cls("Anonymous")
user = User.anonymous()
print(user.name)Because the factory calls cls(...) instead of User(...), subclasses can inherit it and construct their own type correctly.
Alternative Constructors
Class methods are commonly used for alternative constructors:
from datetime import date
class Person:
def __init__(self, name, birth_year):
self.name = name
self.birth_year = birth_year
@classmethod
def from_age(cls, name, age):
return cls(name, date.today().year - age)Accessing Class State
A class method can read or update class attributes through cls:
class Connection:
default_timeout = 30
@classmethod
def set_default_timeout(cls, seconds):
cls.default_timeout = secondsA static method can technically reference a class by its global name, but doing so couples the method to that exact class and is usually a sign that @classmethod is more appropriate.
Quick Comparison
| Feature | Instance method | @classmethod |
@staticmethod |
|---|---|---|---|
| Implicit first argument | self |
cls |
none |
| Access instance state | yes | no direct instance | no implicit access |
| Access class state | yes | yes | no implicit access |
| Common use | object behavior | factories, class-wide behavior | related utility function |
When a Module Function Is Better
Not every utility needs to live inside a class. If a function does not benefit from the class namespace, a normal module-level function is often simpler.
Conclusion
Use instance methods for object-specific behavior, @classmethod when the method needs the class or should construct subclass-aware instances, and @staticmethod for small related utilities that require neither self nor cls.