0
0
PythonConceptBeginner · 3 min read

What is classmethod decorator in Python: Explanation and Example

The @classmethod decorator in Python marks a method to receive the class itself as the first argument instead of an instance. This allows the method to access or modify class state, not instance state, making it useful for factory methods or alternative constructors.
⚙️

How It Works

Imagine a class as a blueprint for making objects. Normally, methods inside a class work with individual objects made from that blueprint. These methods get the object itself as the first input, called self.

But sometimes, you want a method that works with the blueprint itself, not any single object. The @classmethod decorator changes a method so it gets the class (the blueprint) as the first input instead of an object. This first input is usually named cls.

This means the method can look at or change things that belong to the whole class, like shared settings or ways to create new objects differently. It’s like having a tool that works on the blueprint to make new designs or change rules for all objects.

💻

Example

This example shows a class with a @classmethod that creates an object from a string. It uses the class itself to make the new object.

python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def from_string(cls, info_str):
        name, age = info_str.split(',')
        return cls(name, int(age))

# Create a Person object using the class method
person = Person.from_string('Alice,30')
print(person.name)  # Alice
print(person.age)   # 30
Output
Alice 30
🎯

When to Use

Use @classmethod when you need a method that works with the class itself, not just one object. Common uses include:

  • Alternative constructors: Create objects in different ways, like from strings or files.
  • Accessing or modifying class-level data shared by all objects.
  • Factory methods that decide which subclass to create based on input.

For example, if you want to create a user from a database record or a formatted string, a class method can handle that neatly.

Key Points

  • @classmethod methods receive the class as the first argument, usually named cls.
  • They can be called on the class itself, without creating an instance first.
  • Useful for alternative constructors and class-level operations.
  • Different from @staticmethod, which does not receive any automatic first argument.

Key Takeaways

The @classmethod decorator makes a method receive the class, not an instance, as its first argument.
Class methods are great for alternative ways to create objects or work with class-level data.
Use class methods when you want to affect or use the class itself, not just one object.
Class methods are called on the class, so you don’t need to create an object first.
They differ from static methods because they get the class automatically as input.