What is the idiomatic use of @classmethod?
Options
- Methods that need neither the class nor the instance
- Alternative constructors, like
Date.from_iso('2026-01-01')(Correct option) - Making a method private so only the class can call it
- Overriding
__init__to change how objects are created
Answer
Alternative constructors such as Date.from_iso("2026-01-01")
Why
A classmethod receives the class (cls) instead of an object.
Its typical use is an alternative constructor: another way to build an object, for example from a string. Because it calls cls(...), it also builds the right type when used on a subclass.
A staticmethod receives nothing automatically; it is just a normal function kept inside the class.
class Date:
def __init__(self, y, m, d): ...
@classmethod
def from_iso(cls, text):
y, m, d = map(int, text.split("-"))
return cls(y, m, d)Remember
classmethod = alternative constructor.