Python classmethod: @classmethod, cls, and Factory Methods

Learn Python classmethod with examples using @classmethod, cls, class variables, factory methods, return cls, and the difference between class methods, instance methods, and static methods.

Published

Updated

Read time 8 min read

Reviewed byDeepak Prasad

Python classmethod: @classmethod, cls, and Factory Methods

This page is for you if you already know how to define a class in Python and want a practical handle on classmethod: what cls is, how it differs from instance and static methods, and why return cls(...) shows up in factory methods. The flow is example-heavy first, then comparisons and pitfalls.

The language reference describes @classmethod as a decorator that wraps a function into a method: the first parameter receives the class object, usually named cls, instead of the instance (self). See the built-in classmethod and the data model for the formal rules.

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.


What is classmethod in Python?

A class method is a function defined on the class that always receives the class as its first argument when you call it. You mark it with @classmethod so Python passes that class (not an instance) as cls. That is the same mechanism the docs describe: the method is bound to the class, and the first parameter is the class object.

Here is a minimal pattern many codebases use: build an instance without calling the constructor with raw arguments.

python
class Car:

    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

    @classmethod
    def from_string(cls, data):
        brand, model = data.split("-", 1)
        return cls(brand, model)


car = Car.from_string("Toyota-Camry")
print(car.brand, car.model)
Output

Calling Car.from_string(...) runs the class method with cls set to Car, and return cls(brand, model) builds a Car the same way Car(...) would.


Python @classmethod syntax

Put @classmethod directly above the def. The first parameter must be the class slot; the name cls is only a convention, but everyone expects it.

python
class Settings:

    mode = "development"

    @classmethod
    def change_mode(cls, new_mode):
        cls.mode = new_mode
Output

You can call it on the class (Settings.change_mode("production")) or on an instance (Settings().change_mode("test")); in both cases Python passes Settings as cls (or the actual runtime class of the instance).


What does cls mean in Python?

cls is the class object for the current call. It behaves like self in the sense that it is injected for you, but it refers to the class, not one instance.

That matters for inheritance: if a subclass calls an inherited class method, cls is the subclass, not the parent. That single rule is why alternative constructors almost always use return cls(...) instead of return ParentClass(...).

python
class Example:

    @classmethod
    def who(cls):
        print(cls.__name__)


class Sub(Example):
    pass


Example.who()
Sub.who()
Output

You should see Example then Sub, because each call passes the class that was used on the left of the dot.


Basic classmethod example

Shared counters and flags are a second common use: one variable on the class, updated through a class method.

python
class Counter:

    total = 0

    @classmethod
    def increment(cls):
        cls.total += 1


Counter.increment()
Counter.increment()
print(Counter.total)
Output

After two increments, the printed total is 2. Every instance would read the same Counter.total unless you shadow it on an instance.


Access class variables using classmethod

Read shared configuration or defaults through cls so subclasses can override the attribute on their own class.

python
class Product:

    tax_percent = 5

    @classmethod
    def get_tax(cls):
        return cls.tax_percent


print(Product.get_tax())
Output

Modify class variables using classmethod

Assigning through cls.attr_name updates the attribute on the class object, which is what you want for shared settings (with the usual caution: mutable class attributes are shared across all instances unless you copy per instance in __init__).

python
class AppConfig:

    debug = False

    @classmethod
    def set_debug(cls, value):
        cls.debug = value


AppConfig.set_debug(True)
print(AppConfig.debug)
Output

classmethod as a factory method

A factory class method is an extra constructor: it parses input, validates, then returns cls(...). That keeps __init__ simple while supporting several construction paths (string, dict, JSON, and so on). The Python constructor guide covers what runs inside __init__ once cls(...) returns.

Return cls from a classmethod

return cls(...) constructs an instance of whatever class was used in the call. With inheritance, cls can be a subclass, so factories stay correct without repeating the class name.

python
class User:

    def __init__(self, name):
        self.name = name

    @classmethod
    def from_string(cls, text):
        return cls(text.strip())


class Admin(User):
    pass


u = User.from_string("  ann  ")
a = Admin.from_string("  bob  ")
print(u.name, type(u).__name__)
print(a.name, type(a).__name__)
Output

Admin.from_string passes cls as Admin, so you get an Admin instance. A less flexible pattern is return User(name), which would always build a User even when called on Admin.

Create object from string

Splitting or parsing a single string into fields fits a class method so callers do not duplicate parsing logic.

python
class Car:

    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

    @classmethod
    def from_string(cls, data):
        brand, model = data.split("-", 1)
        return cls(brand, model)
Output

Create object from dictionary or JSON

The same idea works for a dict or for JSON text: unpack into return cls(...).

python
class Database:

    def __init__(self, host, port):
        self.host = host
        self.port = port

    @classmethod
    def from_config(cls, config):
        return cls(config["host"], config["port"])


db = Database.from_config({"host": "localhost", "port": 3306})
print(db.host, db.port)
Output
python
import json


class Person:

    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def from_json(cls, json_data):
        data = json.loads(json_data)
        return cls(data["name"], data["age"])


p = Person.from_json('{"name": "John", "age": 30}')
print(p.name, p.age)
Output

Unit conversion before construction is the same pattern: normalize input, then return cls(...) with the value your __init__ already expects.

python
class Temperature:

    def __init__(self, celsius):
        self.celsius = celsius

    @classmethod
    def from_fahrenheit(cls, fahrenheit):
        celsius = (fahrenheit - 32) * 5 / 9
        return cls(celsius)


t = Temperature.from_fahrenheit(86)
print(round(t.celsius, 2))
Output

classmethod vs instance method vs staticmethod

  • Instance methods take self and read or change per-object state.
  • Class methods take cls and are meant for class-level behavior and factories.
  • Static methods take neither; they are namespaced like plain functions. They do not receive cls, but they can still read a class variable if they use the class name (or an argument), because Python does not block that lookup.
Feature Class method Instance method Static method
Decorator @classmethod (none) @staticmethod
First parameter cls self None
Gets class automatically Yes Through the instance when you have one No
Gets instance automatically No Yes No
Good for Factory methods, class state Object behavior Utility logic grouped with the class
python
class Demo:

    class_value = 5

    def instance_method(self):
        print("instance", self.class_value)

    @classmethod
    def class_method(cls):
        print("class", cls.class_value)

    @staticmethod
    def static_method():
        print("static", Demo.class_value)


obj = Demo()
obj.instance_method()
Demo.class_method()
Demo.static_method()
Output

For a deeper comparison of static methods, see the Python staticmethod article.


classmethod with inheritance

When a base class defines @classmethod def make(cls): return cls(), subclasses inherit it unchanged but still get their own type in cls, so Sub.make() returns a Sub. If you override and still want parent behavior, you can call super().method(...) from the subclass class method the same way you would elsewhere—see Python super() for MRO details.

python
class Animal:

    @classmethod
    def describe(cls):
        return f"I am {cls.__name__}"


class Dog(Animal):
    pass


print(Dog.describe())
Output

When should you use classmethod?

Use a class method when the natural first argument is the class: alternative constructors and parsers that end in return cls(...), counters or defaults stored on the class, or any logic that should respect subclasses through cls. It is the usual tool for “many ways to build an instance” while keeping __init__ a simple field assignment.


When not to use classmethod

  • If the method needs instance data (self.name, and so on), use an instance method.
  • If the logic does not use the class or any instance, prefer @staticmethod or a plain module-level function; classmethod is not a free pass to avoid self.
  • Do not use classmethod only to avoid creating an object first; pick the method type by what data the function truly needs.
  • Do not store per-object state in class variables; use self attributes in __init__ so each instance has its own values (watch mutable defaults on the class in particular).

Common mistakes with classmethod

  • Forgetting @classmethod, so Python treats the first parameter as self and calls break when you invoke it on the class.
  • Naming the first parameter self in a class method; readers expect cls, and confusion spreads into reviews and tutorials.
  • Reading instance-only attributes inside a class method: there is no instance in the arguments unless you pass one in explicitly.
  • Using classmethod for generic utilities that never touch the class; a static method or function is clearer.
  • Returning a fixed class in a factory (return User(name)) when return cls(name) would keep subclasses correct.
  • Treating class variables as if they were per-instance without realizing every object shares the same mutable object until you assign on self.

Python classmethod quick reference table

Feature Class method Instance method Static method
Decorator @classmethod (none) @staticmethod
First parameter cls self None
Gets class automatically Yes Through the instance No
Gets instance automatically No Yes No
Callable from class Yes No Yes
Callable from instance Yes Yes Yes
Good for Factory methods, class state Object behavior Utility logic

Summary

@classmethod marks a method that receives the class as cls. Use it for factories with return cls(...), for reading or updating data stored on the class, and whenever subclasses must see their own class in cls. Instance methods own per-object behavior with self; static methods are independent helpers that do not get cls or self injected but can still refer to the class by name if they need class-level data. For context on classes and __init__, revisit the Python class example guide, then keep class methods narrow and let cls drive correct construction under inheritance.


References


Frequently Asked Questions

1. What is a classmethod in Python?

A classmethod is bound to the class: Python passes the class as the first argument (conventionally cls). Define it with the @classmethod decorator on the method.

2. What does cls mean in Python?

In a class method, cls is the class object that received the call. It may be a subclass when the method is inherited, which is why factories use return cls(...) instead of hard-coding the class name.

3. How is classmethod different from staticmethod?

classmethod receives cls as the first argument and can use it for class state and factories. staticmethod receives neither cls nor self automatically; it can still read class variables by writing the class name explicitly.

4. When should you use classmethod in Python?

Use classmethod for alternative constructors and factories (return cls(...)), for logic that reads or updates class-level data, and when subclasses must get their own type through cls.

5. Can a classmethod be called from an instance?

Yes. obj.method() and Class.method() both work; Python still passes the class as cls, not the instance.
Bashir Alam

Data Analyst and Machine Learning Engineer

Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and …