liveBook · Manning

Class method

As explained in Python How-To

A class method is a method associated with a class that receives the class as its first argument and can access class-level state and behavior.

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

How Python How-To covers it

How deep it goes
Defines @classmethod and cls, demonstrates constructor use, and stops short of deeper implementation internals.
Examples
Demonstrates Task construction from dictionaries and text, plus unittest checks for both class methods.
What it assumes
Assumes familiarity with custom classes and constructors while distinguishing class methods from instance and static methods.
What you can do after
Build it from scratch by defining factory methods with @classmethod, cls, and constructor calls, then test them with unittest.
How it connects
Connects class methods with class attributes, constructors, instance methods, static methods, and factory methods.

Also explained in

Compare how 3 books explain class method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.