In this lesson, you will learn how to create methods that operate on the class itself rather than on individual objects by using the @classmethod decorator.
Beyond the Instance
So far, most methods you have written involve the self parameter, which allows the method to access a specific object's data. However, there are times when you need a method that cares about the class as a whole rather than a single instance.
By using the @classmethod decorator, you tell Python that the method should receive the class itself as its first argument (conventionally named cls) instead of a specific instance (self).
Accessing Shared State
Class methods are perfect for interacting with class-level attributes—the variables shared by every instance of that class. Imagine you are building a Robot class and you want to keep track of how many robots have been activated.
class Robot:
activation_count = 0 # A shared class attribute
def __init__(self, name):
self.name = name
Robot.activation_count += 1
@classmethod
def get_total_robots(cls):
# We access the class via 'cls' instead of 'self'
return f"Total robots active: {cls.activation_count}"
# Creating instances
bot1 = Robot("Alpha")
bot2 = Robot("Beta")
# Calling the class method directly on the class
print(Robot.get_total_robots())
In this example, get_total_robots doesn't need to know about "Alpha" or "Beta." It only needs to know about the Robot class to read the activation_count. By using the @classmethod decorator, we make it clear that this function is designed to work with the class's blueprint state.
When you define a method this way, you can call it using Robot.get_total_robots() without needing to create an object first. This is a clean way to organize logic that belongs to the "factory" or "category" of the objects, rather than the objects themselves.
Key Takeaway: Use the @classmethod decorator to define methods that interact with class-level state by accepting cls as their first parameter instead of self.