all Python 3OOPterm
@classmethod
classes
A class method. Its first parameter is cls (a reference to the class). Used for alternative constructors.
Syntax
@classmethod
def method(cls, ...): ...
cls is whichever class the method was actually called on, so in a subclass cls(...) builds an instance of the subclass, not the parent — exactly why alternative constructors rely on classmethod. If the factory doesn't need the class at all, reach for staticmethod or a plain function instead. Older tutorials stack @classmethod on top of @property to get a “class property”: that worked in 3.9–3.12, was deprecated in 3.11 and removed in 3.13 — now A.name returns a bound method, not the value.
Examples
class Date:
def __init__(self, y, m, d):
self.y, self.m, self.d = y, m, d
@classmethod
def from_string(cls, s):
y, m, d = map(int, s.split('-'))
return cls(y, m, d)
d = Date.from_string('2024-03-15')
print(d.y, d.m, d.d) # → 2024 3 15
class Dog:
count = 0
def __init__(self, name):
self.name = name
Dog.count += 1
@classmethod
def get_count(cls):
return cls.count
Dog('Rex'); Dog('Max')
print(Dog.get_count()) # → 2
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
@classmethod
def from_fahrenheit(cls, f):
return cls((f - 32) * 5/9)
@classmethod
def from_kelvin(cls, k):
return cls(k - 273.15)
t = Temperature.from_fahrenheit(212)
print(round(t.celsius)) # → 100
class Pizza:
ingredients = []
def __init__(self, ingredients):
self.ingredients = ingredients
@classmethod
def margherita(cls):
return cls(['mozzarella', 'tomato'])
@classmethod
def hawaiian(cls):
return cls(['mozzarella', 'tomato', 'pineapple'])
p = Pizza.margherita()
print(p.ingredients) # → ['mozzarella', 'tomato']
# Через экземпляр тоже работает
class A:
x = 10
@classmethod
def get_x(cls):
return cls.x
a = A()
print(a.get_x()) # → 10
# Наследование + classmethod
class Animal:
@classmethod
def make(cls, name):
obj = cls.__new__(cls)
obj.name = name
return obj
class Cat(Animal):
pass
cat = Cat.make('Whiskers')
print(type(cat).__name__, cat.name) # → Cat Whiskers
# Python 3.13+
class A:
@classmethod
@property
def name(cls):
return cls.__name__
print(type(A.name).__name__) # → method — а не 'A': цепочка удалена в 3.13
See also
Open in the full glossarydocs.python.orgReport an inaccuracy