Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python classmethod Decorator Explained with Examples

Learn how the Python classmethod decorator works, how it differs from staticmethod, and when to use it for factory methods and inheritance.

~4 min readPython
#classmethod#python decorators#staticmethod#factory methods
Diagram showing a classmethod decorator binding a method to the class rather than an instance, with a class box and an arrow pointing to the class

The @classmethod decorator converts a method into a class method: the method receives the class as its first argument instead of an instance. It is a standard Python tool for factory methods, alternative constructors, and class-level logic that needs to respect inheritance. Understanding how it binds to the class rather than an instance is key to using it correctly.

What the @classmethod Decorator Does

When you apply @classmethod to a method, the method is bound to the class on which it is called. The first parameter, conventionally named cls, receives that class. This is true whether the method is invoked on the class or on an instance.

python
class MyClass: @classmethod def create(cls, value): return cls(value) def __init__(self, value): self.value = value obj = MyClass.create(10) print(obj.value) # 10

In this example, create receives MyClass as cls and returns a new instance. If you call obj.create(20) on an instance, cls is still the instance's class, not the instance itself. This is the fundamental difference from an instance method, which receives self.

Class methods, static methods, and instance methods

To decide when to use @classmethod, compare it with the other two method types. The table below summarizes the key differences.

Method typeFirst argumentAccess to instance stateAccess to class stateTypical use
Instance methodselfYesVia self.__class__Behavior that depends on instance data
Class methodclsNoYesFactory methods, alternative constructors
Static methodnoneNoNoUtility functions that don't need class context

A class method can access class attributes and other class methods through cls. It cannot access instance attributes because it has no reference to a specific instance. A static method has no automatic reference to either the class or an instance, so it behaves like a plain function that happens to live inside the class namespace.

Using @classmethod for Alternative Constructors

The most common use of @classmethod is to provide alternative ways to create an instance, often called factory methods. Instead of overloading __init__, you define a class method that parses a different input format and returns an instance of the class.

python
class Person: def __init__(self, name, age): self.name = name self.age = age @classmethod def from_string(cls, data): name, age = data.split(',') return cls(name, int(age)) p = Person.from_string('Alice,30') print(p.name) # Alice print(p.age) # 30

Here, from_string parses the comma-separated string and calls cls(name, int(age)). Using cls instead of a hard-coded class name ensures that if you call the method on a subclass, it returns an instance of that subclass rather than the parent class.

How @classmethod Behaves with Inheritance

The value of @classmethod becomes clearer with inheritance. Because cls is the actual class on which the method is called, polymorphic behavior works naturally.

python
class Animal: @classmethod def make_sound(cls): return cls().sound() def sound(self): return 'Generic sound' class Dog(Animal): def sound(self): return 'Woof' print(Dog.make_sound()) # Woof

When you call Dog.make_sound(), cls is Dog, so cls().sound() invokes Dog.sound(). A static method would not have access to cls, so it would have to hard-code a class name, breaking this polymorphic behavior. Prefer a class method when the method needs to be overridden or must work with subclasses.

Common Mistakes and Edge Cases

One frequent mistake is using @classmethod for a method that actually needs instance data. Because cls does not give access to instance attributes, you cannot read self.attribute inside a class method. If you need instance state, use an instance method.

Calling a class method on an instance also works, but the instance is ignored. For example:

python
class Counter: count = 0 @classmethod def increment(cls): cls.count += 1 c = Counter() c.increment() print(Counter.count) # 1

The increment method modifies the class attribute, not the instance. If you need to modify an instance attribute, this approach will not work.

Also be careful when using cls to create new instances. If the class has required __init__ parameters, the class method must provide them. If a subclass changes the constructor signature, the class method may break unless it is overridden.

Performance and Maintainability Considerations

The @classmethod decorator adds a small amount of overhead compared with @staticmethod because the class is passed as an extra argument. In normal code this overhead is negligible. The larger concern is maintainability: using cls instead of a hard-coded class name keeps code flexible and makes subclassing easier.

Class methods are also a controlled way to update class-level state. However, mutable class attributes can cause subtle problems. A subclass does not automatically get a copy of an inherited mutable attribute; if you mutate it in place, the change is visible through all classes that share the attribute. For example:

python
class A: items = [] @classmethod def add(cls, item): cls.items.append(item) class B(A): pass B.add('x') print(A.items) # ['x']

Because items is a list and append mutates it in place, A and B share the same list. If you want each class to have its own list, assign a new list to cls.items instead of mutating the existing list.

In short, choose @classmethod when you need access to the class for polymorphism, factory behavior, or subclass-aware logic. Choose @staticmethod when the method is a pure utility that does not depend on class or instance context.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.