A class method is a method associated with a class rather than one particular instance. Python marks it with @classmethod, and its first parameter conventionally named cls refers to the class. This lets the method access class-level behavior and create instances through the class constructor. section 8.2.3
Use a class method when a method needs the class itself:
- Accept structured input such as a dictionary or text representation. section 8.2.3 section 13.4.1
- Construct an instance with cls(...) instead of hard-coding the class name. section 8.2.3
- Choose it instead of an instance method when no existing instance is required, and instead of a static method when class access matters. section 8.2 section 8.6
Creating a Task from a dictionary
class Task: def __init__(self, title, desc, urgency): self.title = title self.desc = desc self.urgency = urgency self._status = "created" @classmethod def task_from_dict(cls, task_dict): return cls( task_dict["title"], task_dict["desc"], task_dict["urgency"] ) task_dict = {"title": "Laundry", "desc": "Wash clothes", "urgency": 3} task = Task.task_from_dict(task_dict) print(task.__dict__) # {'title': 'Laundry', 'desc': 'Wash clothes', 'urgency': 3, 'status': 'created', 'tags': []} section 8.2.3
Listing 8.6 Creating a class method
class Task:
def __init__(self, title, desc, urgency):
self.title = title
self.desc = desc
self.urgency = urgency
self._status = "created"
@classmethod
def task_from_dict(cls, task_dict):
title = task_dict["title"]
desc = task_dict["desc"]
urgency = task_dict["urgency"]
task_obj = cls(title, desc, urgency)
return task_obj
Inspect the complete class-method listing, including @classmethod, cls, dictionary extraction, and constructor-based instance creation. section 8.2.3


