Python classmethod function
last modified November 29, 2026 Python 3.15
In this article we show how the classmethod builtin turns a function into a method that receives the class instead of an instance.
The decorator is applied inside a class body. It returns a descriptor object that binds the function to whichever class it is read from, so the first argument is the class itself, conventionally named cls.
Alternative constructors built with class methods are shown in Python methods and Python static methods; they are not repeated here. The binding mechanism belongs to Python __get__ Method.
The decorator and the object it creates
Inside the class body, @classmethod replaces the function with a classmethod object. That object keeps the original function in its __func__ attribute and binds it when it is read through the class.
class Falcon:
species = 'peregrine'
@classmethod
def describe(cls):
return f'{cls.__name__}: {cls.species}'
raw = vars(Falcon)['describe']
print(type(raw))
print(raw.__func__.__qualname__)
print(type(Falcon.describe))
print(Falcon.describe())
print(Falcon().describe())
The class dictionary holds a classmethod object, but reading Falcon.describe goes through the descriptor protocol and returns a bound method. The bound method's __self__ is the class.
Calling through an instance gives the same result, because the instance only supplies its class. The instance itself is never passed to the function.
$ python decorator_object.py <class 'classmethod'> Falcon.describe <class 'method'> Falcon: peregrine Falcon: peregrine
Binding to the class and its subclasses
The descriptor binds to the class it is accessed through, not to the class where it was defined. That is what makes a class method follow inheritance.
class Falcon:
@classmethod
def speak(cls):
return f'{cls.__name__} calls'
class Heron(Falcon):
pass
print(Falcon.speak())
print(Heron.speak())
print(Falcon().speak())
raw = vars(Falcon)['speak']
bound = raw.__get__(None, Heron)
print(bound())
print(bound.__self__ is Heron)
The inherited call on Heron passes Heron as cls, so the name in the message changes. Reading the raw descriptor and binding it by hand with __get__ produces the same method.
This is the mechanism to remember when a class method builds an object: cls(...) creates an instance of the subclass that was used for the call, not of the class that defined the method.
$ python binding.py Falcon calls Heron calls Falcon calls Heron calls True
Cooperation with super
A subclass can extend a class method and still call the parent version with super(). The zero-argument form works inside a class method just as it does inside an instance method.
class Bird:
sound = 'call'
@classmethod
def signature(cls):
return f'{cls.__name__} makes a {cls.sound}'
class Falcon(Bird):
sound = 'screech'
@classmethod
def signature(cls):
return 'fast ' + super().signature()
print(Bird.signature())
print(Falcon.signature())
print(Falcon().signature())
super() starts the lookup after Falcon in the method resolution order, finds the parent class method, and binds it to Falcon again. The parent therefore reads Falcon.sound, not Bird.sound.
The result is that both parts of the message describe the subclass. This pattern is common for class-level configuration, where each subclass adds a detail and the base class formats the whole value.
$ python super_call.py Bird makes a call fast Falcon makes a screech fast Falcon makes a screech
A registry filled by subclasses
Class methods are a natural fit for a registry keyed by class attributes. The classes can register themselves at definition time, and a class method performs the lookup.
class Exporter:
formats = {}
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
Exporter.formats[cls.extension] = cls
@classmethod
def for_extension(cls, extension):
try:
return cls.formats[extension]
except KeyError:
raise ValueError(f'unsupported extension: {extension}') from None
class CsvExporter(Exporter):
extension = '.csv'
class JsonExporter(Exporter):
extension = '.json'
print(sorted(Exporter.formats))
print(Exporter.for_extension('.csv').__name__)
try:
Exporter.for_extension('.xml')
except ValueError as e:
print('ValueError:', e)
__init_subclass__ is an implicit class method: Python calls it on the parent with the new class as the first argument, right after the subclass body has been executed. That is why cls.extension is already available.
The lookup uses the same class method but does not depend on the class it is called on, since the table lives on Exporter. A missing key is turned into a clear ValueError instead of a bare KeyError.
$ python registry.py ['.csv', '.json'] CsvExporter ValueError: unsupported extension: .xml
Why a class property needs a descriptor now
Stacking @classmethod over @property used to create a class-level property. The behaviour was deprecated in Python 3.11 and removed in 3.13, so on 3.15 the combination no longer works.
class Falcon:
@classmethod
@property
def label(cls):
return 'falcon'
print(type(Falcon.label))
try:
print(Falcon.label())
except TypeError as e:
print('TypeError:', e)
class classproperty:
def __init__(self, func):
self.func = func
def __get__(self, instance, owner):
return self.func(owner)
class Heron:
name = 'grey heron'
@classproperty
def label(cls):
return cls.name.title()
print(Heron.label)
print(Heron().label)
The class method wraps the property object and binds it like a function, so the result is a bound method whose call raises TypeError. The old shortcut is gone and cannot be restored by changing the decorator order.
A small descriptor replaces it. The __get__ method receives the class as owner and calls the function with it, which gives a computed value on both the class and its instances. The protocol is explained in Python __get__ Method.
$ python class_property.py <class 'method'> TypeError: 'property' object is not callable Grey Heron Grey Heron
Class method or static method
A static method receives nothing implicitly, while a class method receives the class. The difference appears as soon as a subclass changes a class attribute that the method reads.
class Unit:
factor = 1000
@classmethod
def in_base(cls, value):
return value * cls.factor
@staticmethod
def label():
return 'unit'
class Milli(Unit):
factor = 1
print(Unit.in_base(2))
print(Milli.in_base(2))
print(Unit.label())
print(Milli.label())
try:
Unit.in_base()
except TypeError as e:
print('TypeError:', e)
The class method sees Milli.factor when it is called on Milli, so the same code returns a different number. The static method has no class to look at and returns the same text for both.
Use classmethod when the behaviour depends on the class and staticmethod when it does not. Both still need the right number of arguments when called.
$ python vs_static.py 2000 2 unit unit TypeError: Unit.in_base() missing 1 required positional argument: 'value'
Class state belongs to each class
Assigning through cls writes to the class that was used for the call. A subclass therefore gets its own copy of the attribute as soon as a class method changes it.
class Counter:
total = 0
def __init__(self):
type(self).total += 1
@classmethod
def report(cls):
return f'{cls.__name__}: {cls.total}'
class Falcon(Counter):
pass
class Heron(Counter):
pass
Falcon()
Falcon()
Heron()
print(Falcon.report())
print(Heron.report())
print(Counter.report())
try:
vars(Counter)['report']()
except TypeError as e:
print('TypeError:', e)
Each subclass counts its own instances, and the base class stays at zero because no Counter was created. The attribute is created on the subclass the first time it is assigned, which is why the counts do not mix.
The last lines show the raw descriptor again: it has no class to bind to, so calling it directly fails. A class method only becomes a method after attribute access on a class.
$ python class_state.py Falcon: 2 Heron: 1 Counter: 0 TypeError: 'classmethod' object is not callable
Source
Python classmethod() documentation
In this article we have examined the classmethod object, its binding through __get__, inheritance, super(), a self-registering plugin table, the removed class property combination, and the difference from a static method. For factory methods built on class methods, see Python methods and Python static methods.
Author
List all Python tutorials.