Sub topic 10
classmethod and staticmethod
This chapter assumes you know the descriptor protocol (__get__, __set__, __delete__), the difference between data and non-data descriptors, and how functions become bound methods. Earlier chapters cover each of these. Here you will see that classmethod and staticmethod are small non-data descriptors that change what __get__ returns for a function.
The two decorators as descriptors
A function in a class body is a non-data descriptor. Its __get__ returns a bound method that passes the instance as the first argument. classmethod and staticmethod wrap a function in a different descriptor so that __get__ returns something else.
| Decorator | Object stored in the class `__dict__` | What `__get__` returns | First argument of the call |
|---|---|---|---|
| none (plain function) | `function` | method bound to the instance (or the plain function when accessed on the class) | the instance |
| `@classmethod` | `classmethod` | method bound to the class | the class |
| `@staticmethod` | `staticmethod` | the original function, unchanged | none added |
None of the three defines __set__ or __delete__. All of them are non-data descriptors, so the lookup order you already know applies to them.
class C:
@classmethod
def make(cls):
return cls
@staticmethod
def helper(x):
return x * 2
print(type(C.__dict__["make"]).__name__) # classmethod
print(type(C.__dict__["helper"]).__name__) # staticmethod
raw = C.__dict__["make"]
print(raw.__get__(None, C) == C.make) # True
print(C.__dict__["helper"].__get__(None, C) is C.helper) # TrueReading C.__dict__["make"] bypasses the descriptor protocol and gives you the raw classmethod object. Calling __get__ by hand does what C.make does.
A pure-Python model
The Python documentation describes both decorators with short equivalents. These models leave out details such as attribute copying, but they show the mechanism.
import types
class MyClassMethod:
def __init__(self, func):
self.__func__ = func
def __get__(self, obj, objtype=None):
if objtype is None:
objtype = type(obj)
return types.MethodType(self.__func__, objtype)
class MyStaticMethod:
def __init__(self, func):
self.__func__ = func
def __get__(self, obj, objtype=None):
return self.__func__
class Demo:
@MyClassMethod
def kind(cls):
return cls.__name__
@MyStaticMethod
def add(a, b):
return a + b
class SubDemo(Demo):
pass
print(Demo().kind()) # Demo
print(SubDemo.kind()) # SubDemo
print(Demo.add(2, 3)) # 5
print(Demo().add(2, 3)) # 5MyClassMethod.__get__ ignores obj except to find the class when objtype is missing. Whether you write Demo.kind or Demo().kind, the function is bound to a class. MyStaticMethod.__get__ ignores both arguments and hands back the function, so no binding happens.
The class you get depends on how you access it
The cls that a class method receives is the class used for the lookup, not the class that defines the method. type(obj) is used for instance access, and SubDemo above shows this for class access. This is why class methods work as alternative constructors that respect inheritance.
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
@classmethod
def from_string(cls, text):
year, month, day = (int(part) for part in text.split("-"))
return cls(year, month, day)
def __repr__(self):
return f"{type(self).__name__}({self.year}, {self.month}, {self.day})"
class LoggedDate(Date):
pass
print(Date.from_string("2026-11-26")) # Date(2026, 11, 26)
print(LoggedDate.from_string("2026-11-26")) # LoggedDate(2026, 11, 26)If from_string were a static method that called Date(...) directly, LoggedDate.from_string would return a plain Date. Writing cls(...) keeps subclasses working without overriding the constructor.
Where each lookup step happens
When you write Date.from_string, Python uses type.__getattribute__ because Date is an object whose type is type. It searches the MRO of Date for from_string, finds a classmethod, and calls its __get__(None, Date). When you write date_obj.from_string, object.__getattribute__ finds the same descriptor on the type. It checks that the descriptor is not a data descriptor, then checks the instance __dict__, then calls __get__(date_obj, Date).
Behaviors that follow from the model
Instance attributes can shadow them
Because both decorators are non-data descriptors, an entry in the instance __dict__ wins over them.
class Tool:
@classmethod
def build(cls):
return cls.__name__
@staticmethod
def ping():
return "pong"
t = Tool()
t.__dict__["build"] = "shadowed"
print(t.build) # shadowed
print(Tool.build()) # Tool
print(t.ping()) # pongClass access still works, because the instance __dict__ is not consulted when you look up an attribute on the class.
Static methods are mostly a convenience
A static method is a plain function that happens to live in a class namespace. Its main effect is to stop the automatic binding. Without the decorator, Tool().ping() would pass the instance as an unexpected first argument and raise a TypeError. A function defined at module level is often a clearer choice, so use staticmethod when the function belongs with the class for naming or discovery reasons.
Since Python 3.10, the staticmethod object itself is callable and exposes __wrapped__. Calling Tool.__dict__["ping"]() works on current versions, but fails on 3.9 and earlier.
Overriding keeps the decorator in play
A subclass that overrides a class method must decorate its version with @classmethod too. If it defines a plain function under the same name, then Sub.build follows the function rules, and Sub.build() fails because no instance or class is passed.
Wrapping other descriptors
Python 3.9 let classmethod wrap other descriptors such as property, so a class-level property could be written by stacking decorators. That behavior was deprecated in Python 3.11 and removed in 3.13. For class-level computed attributes, write a small custom descriptor whose __get__ uses its objtype argument, or define the property on a metaclass.
class ClassProperty:
def __init__(self, func):
self.func = func
def __get__(self, obj, objtype=None):
if objtype is None:
objtype = type(obj)
return self.func(objtype)
class Config:
@ClassProperty
def label(cls):
return f"config:{cls.__name__}"
print(Config.label) # config:Config
print(Config().label) # config:ConfigThis ClassProperty has no __set__, so it is a non-data descriptor. Assigning Config().label = "x" creates an instance attribute that hides it, and assigning Config.label = "x" replaces the descriptor on the class without calling anything.
Common mistakes
- Calling a class method on an instance and expecting the instance to be passed. Only the class is bound, so
selfstate is not available. - Hard-coding the class name inside a class method (
return Date(...)), which breaks subclasses. - Forgetting
@staticmethodon a helper and then calling it through an instance. The instance becomes the first argument. - Reading
Class.__dict__["name"]and calling the result like a method on older Python versions. UseClass.nameor call__get__explicitly. - Relying on stacked
@classmethod @property, which no longer works on Python 3.13 and later.
Checking your understanding
Exercise
A class defines @classmethod def create(cls): return cls(). A subclass Child(Base) does not override create. What does Child.create() return, and which __get__ call produced the bound method? Why can Child().create() return the same kind of object?
Show answer
It returns an instance of Child. Python searches Child.__mro__, finds the classmethod object in Base.__dict__, and calls __get__(None, Child), which binds the function to Child. For Child().create(), object.__getattribute__ finds the same non-data descriptor and calls __get__(instance, Child). The classmethod implementation uses the type, not the instance, as the bound object, so cls is again Child and the result is again a Child instance.
Exercise
Given class K: @staticmethod def f(): return 1, what does k = K(); k.__dict__["f"] = lambda: 2; k.f() return, and what does K.f() return? Explain using the descriptor type.
Show answer
k.f() returns 2 and K.f() returns 1. A staticmethod is a non-data descriptor, so the instance __dict__ entry takes precedence for instance access. Class access does not look in the instance __dict__, so K.f still goes through the staticmethod's __get__ and returns the original function.