Class methods
A class method receives the class as its first argument instead of an instance. It is the standard way to write alternative constructors and any behaviour that belongs to the class as a whole rather than to one object.
Detailed Explanation
A normal method is called on an object and gets that object as self. A class method is called on the class and gets the class as cls. You create one with the @classmethod decorator. You can call it on the class (Order.from_csv_row(...)) or on an instance (order.from_csv_row(...)) — either way the first argument is the class, never the instance.
The reason this exists is that Python allows exactly one __init__ per class. Java or C++ would give you four overloaded constructors: one from a database row, one from a CSV line, one from a JSON payload, one from raw fields. Python cannot overload, so the idiom is a single __init__ that takes the canonical fields and a set of class methods that parse other formats and call it. datetime.fromtimestamp, dict.fromkeys and int.from_bytes are all this pattern in the standard library.
The important detail is the last line of such a method: return cls(...), not return Order(...). Because cls is whatever class the method was actually called on, a subclass inherits the alternative constructor and gets instances of itself back. Hardcoding the class name silently breaks every subclass, which is the single most common mistake with this feature.
The second use is behaviour that reads or mutates class-level state. A registry of subclasses, a cache shared by all instances, or a configured default belongs on the class, and a class method is the natural place to touch it. Be aware of a trap here: assigning cls.counter = 0 inside a class method creates the attribute on the subclass it was called on, shadowing the parent's, rather than updating the parent. If you mean the parent's attribute, name it explicitly.
Compare the three method kinds. A regular method needs an instance and gets self. A class method needs no instance and gets cls. A static method gets nothing implicit and is a plain function that happens to live in the class body. Choose by what the code actually needs: if it uses instance state use a regular method, if it needs the class (to construct it, or to read class attributes polymorphically) use a class method, and if it needs neither use a static method or a module-level function.
One nuance about inheritance. Class methods are inherited and they are polymorphic on cls, which makes them behave differently from Java's static methods. A Java static method is resolved on the compile-time type and cannot be overridden in any useful sense. A Python class method is resolved through the MRO of the class you called it on, so a subclass can override it and the override wins. That is a genuine capability, not a syntax difference, and it is why the "class methods are just static methods" intuition from Java misleads people.
Finally, __init_subclass__ and __class_getitem__ are implicitly class methods; you do not need the decorator on them.
Code Examples
from __future__ import annotations
class Order:
def __init__(self, sku: str, qty: int):
self.sku = sku
self.qty = qty
@classmethod
def from_csv_row(cls, row: str) -> "Order":
"""Alternative constructor. `cls` is the class it was called on."""
sku, qty = row.split(",")
return cls(sku, int(qty)) # cls(...), NOT Order(...)
def __repr__(self) -> str:
return f"{type(self).__name__}(sku={self.sku!r}, qty={self.qty})"
class PriorityOrder(Order):
pass # adds nothing, inherits everything
print(Order.from_csv_row("A1,2")) # Order(sku='A1', qty=2)
print(PriorityOrder.from_csv_row("A1,2")) # PriorityOrder(sku='A1', qty=2)class Connection:
"""Class-level state: one pool shared by every instance."""
_pool: list["Connection"] = [] # lives on the class, not the instance
max_pool_size = 5
def __init__(self, dsn: str):
self.dsn = dsn
@classmethod
def acquire(cls, dsn: str) -> "Connection":
if cls._pool:
return cls._pool.pop() # reuse a parked connection
return cls(dsn)
@classmethod
def release(cls, conn: "Connection") -> None:
if len(cls._pool) < cls.max_pool_size:
cls._pool.append(conn) # mutating the shared list is fine
c = Connection.acquire("postgres://localhost/app")
Connection.release(c)
print(Connection.acquire("postgres://localhost/app") is c) # True, reused
class TestConnection(Connection):
max_pool_size = 1 # overriding a class attribute works
# because acquire/release read cls.*
print(TestConnection.max_pool_size) # 1
print(Connection.max_pool_size) # 5, the parent is untouchedCommon Gotchas
Hardcoding the class name breaks subclasses
writing `return Order(...)` instead of `return cls(...)` means `PriorityOrder.from_csv_row(...)` hands you a plain `Order`. The bug is invisible until someone subclasses you, and then it is very confusing.
Assigning to `cls.attr` writes to the subclass, not the parent
`cls.counter += 1` called on a subclass reads the parent's value, then creates a new attribute on the subclass. Every subclass ends up with its own counter. Use `Base.counter += 1` when you want one shared value.
Mutable class attributes are shared by everything
`_pool = []` is created once, at class-definition time. All instances and all subclasses that do not override it see the same list. That is the point for a pool and a disaster for anything meant to be per-instance.
Calling a class method on an instance still passes the class
`order.from_csv_row("A1,2")` works and `order` is discarded. It is legal but reads as though instance state is involved, so prefer calling it on the class.