Repaso
EspaƱol
PythonIntermediatePY-31

What is the idiomatic use of @classmethod?

Options

  1. Methods that need neither the class nor the instance
  2. Alternative constructors, like Date.from_iso('2026-01-01') (Correct option)
  3. Making a method private so only the class can call it
  4. 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.

Key terms

Practice this question in Repaso