classmethod() is a built-in Python function (and decorator) that transforms a regular method into a **class method** — one that receives the class itself (cls) as its first argument instead of an instance (self). Class methods can be called on the class or any instance, making them ideal for factory methods, alternative constructors, class-level utilities, and operations that don’t depend on instance state. In 2026, @classmethod remains a core tool in Python — used in data science (alternative DataFrame constructors), software engineering (singleton patterns, configuration factories), and frameworks (FastAPI dependencies, SQLAlchemy models, dataclasses) — enabling clean, reusable, and testable class-level logic.
Here’s a complete, practical guide to using classmethod() in Python: basic decorator usage, alternative constructors, class-level state, real-world patterns (earthquake data factories, configuration, validation), and modern best practices with type hints, inheritance, performance, and integration with dataclasses/Pydantic/Dask.
Basic @classmethod — define methods that receive cls instead of self.
class Earthquake:
count = 0 # class-level state
def __init__(self, mag: float, place: str):
self.mag = mag
self.place = place
Earthquake.count += 1
@classmethod
def from_dict(cls, data: dict):
"""Alternative constructor from dictionary (e.g., JSON API response)."""
return cls(data['mag'], data['place'])
@classmethod
def total_count(cls):
"""Class method to access shared state."""
return cls.count
# Usage on class
event = Earthquake.from_dict({'mag': 7.2, 'place': 'Japan'})
print(Earthquake.total_count()) # 1
# Usage on instance (still gets class)
e = Earthquake(6.5, 'Chile')
print(e.total_count()) # 2
Alternative constructors — common use case for @classmethod.
from datetime import datetime
class Earthquake:
def __init__(self, mag: float, place: str, time: datetime):
self.mag = mag
self.place = place
self.time = time
@classmethod
def from_usgs(cls, usgs_dict: dict):
"""Factory from USGS JSON format."""
props = usgs_dict['properties']
geom = usgs_dict['geometry']['coordinates']
time_ms = props['time']
return cls(
mag=props['mag'],
place=props['place'],
time=datetime.fromtimestamp(time_ms / 1000)
)
# Usage
usgs_event = {
'properties': {'mag': 6.8, 'place': 'Alaska'},
'geometry': {'coordinates': [-150.0, 60.0, 20.0]},
'time': 1700000000000 # ms
}
eq = Earthquake.from_usgs(usgs_event)
print(eq.mag, eq.place, eq.time)
Real-world pattern: earthquake catalog factory & class-level stats.
class EarthquakeCatalog:
_events = [] # class-level list of all instances
def __init__(self, mag: float, place: str):
self.mag = mag
self.place = place
EarthquakeCatalog._events.append(self)
@classmethod
def from_jsonl(cls, filepath: str):
"""Load catalog from JSONL file."""
catalog = cls.__new__(cls) # create empty catalog instance
with open(filepath, 'r') as f:
for line in f:
data = json.loads(line)
event = cls(data['mag'], data['place'])
return catalog
@classmethod
def total_events(cls):
return len(cls._events)
@classmethod
def strong_events(cls, threshold=7.0):
return [e for e in cls._events if e.mag >= threshold]
# Usage
catalog = EarthquakeCatalog.from_jsonl('quakes.jsonl')
print(f"Total events: {EarthquakeCatalog.total_events()}")
print(f"Strong events: {[e.place for e in EarthquakeCatalog.strong_events()]}")
Best practices for @classmethod in Python & data workflows. Use for alternative constructors — from_xxx(cls, ...) pattern. Modern tip: combine with @classmethod + @property — for class-level computed properties. Use cls — not hard-coded class name — for proper inheritance. Prefer class methods over static methods — when you need class access. Add type hints — @classmethod def from_dict(cls, data: dict) -> 'Earthquake'. Use in inheritance — subclasses inherit class methods. Use cls.__new__() — for factories that return class instances. Avoid instance state in class methods — keep them stateless or class-state only. Use classmethod as decorator — not function wrapper (legacy). Use in metaclasses — advanced class creation. Use with dataclasses — @classmethod def from_dict(cls, data). Use in Pydantic models — @classmethod def validate(cls, data). Test class methods — assert Earthquake.from_dict({...}).mag == 7.0. Profile performance — class methods have negligible overhead. Use __class__ — in instances to access class dynamically.
classmethod() (or @classmethod) defines methods that receive the class (cls) as first argument — callable on class or instances, perfect for factories, class utilities, and shared state access. In 2026, use for alternative constructors, class-level operations, inheritance-friendly code, and integrate with dataclasses/Pydantic/Dask. Master class methods, and you’ll write reusable, maintainable, and scalable class-level logic in any Python project.
Next time you need class-level behavior — use @classmethod. It’s Python’s cleanest way to say: “This method belongs to the class — call it on the class or any instance.”