Sub topic 2
Alternative Constructors with `@classmethod`
This chapter assumes you can define classes, use instance methods and self, distinguish class attributes from instance attributes, and recognize basic decorator syntax.
Alternative constructors with `@classmethod`
An alternative constructor is a class method that creates an object from a different input format. The usual constructor is __init__, but a class may also create objects from strings, dictionaries, or other objects.
A class method receives the class as its first argument. By convention, that argument is named cls.
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 = map(int, text.split("-"))
return cls(year, month, day)
def describe(self):
return f"{self.year:04d}-{self.month:02d}-{self.day:02d}"
date = Date.from_string("2026-11-26")
print(date.describe()) # 2026-11-26Date.from_string is called on the class, so Python supplies Date as cls. The method converts the text, then calls cls(...) to create the object.
This pattern keeps parsing logic near the class it supports. It also gives callers a clear name for the input format.
Why `cls` matters: class methods and subclasses
A class method receives the class used for the call. If a subclass calls the method, cls refers to that subclass.
class Shape:
@classmethod
def create(cls):
return cls()
class Square(Shape):
pass
shape = Shape.create()
square = Square.create()
print(type(shape).__name__) # Shape
print(type(square).__name__) # SquareSquare.create() passes Square as cls, so cls() creates a Square. If create used Shape() instead, it would always create a Shape, even when called through Square.
The same rule lets subclasses customize construction. A subclass can override __init__, and cls(...) will call that subclass constructor.
Exercise
Why should an alternative constructor return cls(...) instead of Shape(...)?
Show answer
Because cls is the class used for the call, so subclasses receive instances of the subclass.