A receives the class itself (cls) as its implicit first argument—allowing it to access or mutate class-level state and construct instances polymorphically in subclasses (return cls(...))—whereas a receives no implicit first argument (self or cls), functioning as an ordinary utility function namespaced inside the class body.
Basic Example
from datetime import date
class Person:
species = "Homo sapiens"
def __init__(self, name: str, age: int) -> None:
self.name = name
self.age = age
# 1. `@classmethod`: Receives `cls` — ideal for alternative constructors & subclassing
@classmethod
def from_birth_year(cls, name: str, birth_year: int) -> "Person":
return cls(name, date.today().year - birth_year)
# 2. `@staticmethod`: Receives NO `self` or `cls` — pure helper namespaced on the class
@staticmethod
def is_adult(age: int) -> bool:
return age >= 18
class Employee(Person):
pass
# `from_birth_year` called on `Employee` automatically returns an `Employee` instance:
emp = Employee.from_birth_year("Alice", 1995)
print(type(emp).__name__, emp.name, emp.age)
# Output: Employee Alice 31
print(Person.is_adult(emp.age))
# Output: True
Key Details & Edge Cases
- Inheritance & Polymorphism (
cls(...)vs. hardcodedPerson(...)):- Because a
dynamically receives whichever class it was invoked on (Employee.from_birth_year(...)passescls = Employee), callingcls(...)instantiates the subclass, not the base class. If you wrotefrom_birth_yearas areturningPerson(...), callingEmployee.from_birth_year(...)would erroneously return a plainPersoninstead of anEmployee.
- Because a
- Both can be called on either the class (
Person.method()) or an instance (emp.method()):- Calling
emp.from_birth_year(...)still passestype(emp)(Employee) ascls, notemp. Callingemp.is_adult(20)passes only20and ignoresempcompletely.
- Calling
- Accessing or modifying class attributes (
cls.attr):- Use
whenever a method needs to read or update class-level configuration, registries, or counters (cls._registry.append(...)) without hardcoding the class name—this ensures subclasses with overridden class attributes behave properly.
- Use
- When to use a module-level function instead of
:- Unlike Java or C#, Python does not require every function to live inside a class. Prefer
only when the helper is conceptually tied to the class’s domain API (or when subclasses might override that helper viaself.helper()/cls.helper()). Otherwise, a module-level helper function is cleaner and more Pythonic.
- Unlike Java or C#, Python does not require every function to live inside a class. Prefer
- Combining
with@property:- Chaining
+@propertywas briefly supported in Python 3.9–3.10 and deprecated/removed in Python 3.11–3.13 (TypeError: 'classmethod' object is not callable). Use a standardgetter method (Config.get_default()) or a metaclass@propertyinstead.
- Chaining
Comparison of , , and Regular Instance Methods
| Feature | Instance Method (def fn(self)) |
(def fn(cls)) |
(def fn()) |
|---|---|---|---|
| Implicit First Argument | Instance (self) |
Class (cls) |
None |
Can Read/Modify Instance State (self.x)? |
Yes | No | No |
Can Read/Modify Class State (cls.x)? |
Yes (type(self).x) |
Yes (cls.x) |
Only by hardcoding class name |
Polymorphic Across Subclasses (cls(...))? |
Yes | Yes | No (no access to cls) |
| Primary Use Case | Core object behavior operating on instance data. | Alternative constructors (from_json, from_dict) and class-state factories/registries. |
Domain-specific validation or calculation helpers that need neither self nor cls. |
You must log in or register to comment.
