Python class methods are a distinct kind of method that receives the class itself as the first argument rather than receiving an individual instance. Where an instance method operates on a specific object's data through the familiar self parameter, a class method operates on the class as a whole through a parameter conventionally named cls. Class methods are defined by placing the @classmethod decorator on the line immediately above the method definition, a small syntactic addition that tells Python to pass the class instead of the instance when the method is called. Understanding class methods unlocks several important design patterns, most notably the factory method pattern where a class provides multiple ways to construct its instances from different kinds of input data.
The distinction between instance methods, class methods, and the static methods covered in the next article is one of the areas where Python's flexibility can initially feel like ambiguity. An instance method needs an object and receives that object as self. A class method needs the class and receives it as cls. A static method needs neither and receives no automatic argument at all. The choice among the three is not arbitrary; it communicates intent to anyone reading your code. If a method begins with self, it works with object state. If it begins with cls, it works with class-level concerns. If it begins with neither, it is a utility function that happens to live in a class for organizational reasons. This article focuses on the middle category: methods that belong to the class itself rather than to any one instance.
If you have worked through the article on instance methods in Python, you already understand how the self parameter connects a method call to the object it modifies. Class methods follow the same mechanical pattern but substitute the class for the object, which changes what the method can access and what it is useful for. The self parameter gives instance methods access to instance attributes; the cls parameter gives class methods access to class attributes and to the class's constructor, enabling patterns that would be awkward or impossible with instance methods alone.
The @classmethod decorator and the cls parameter
The syntax for defining a class method is straightforward: write the @classmethod decorator on the line before the method definition, and name the first parameter cls instead of self. The decorator is not a suggestion or a comment; it is an instruction to Python's method resolution machinery that changes how the method receives its first argument. Without the decorator, a method whose first parameter is named cls would still receive an instance when called on an object, because Python defaults to instance method binding for any function defined inside a class body.
Here is a class that uses a class method to provide an alternative way to construct instances. The primary constructor accepts individual fields, while the class method accepts a comma-separated string and parses it into the same fields:
class Customer:
def __init__(self, name, email):
self.name = name
self.email = email
@classmethod
def from_string(cls, data):
name, email = data.split(",")
return cls(name.strip(), email.strip())The from_string method is decorated with @classmethod, which means Python passes the Customer class itself as the cls argument. The method splits the input string into a name and an email, strips whitespace from both, and then calls cls to create a new Customer instance with the parsed values. The caller never calls the constructor directly when using this path; the class method encapsulates the parsing and construction logic in one place.
The key line is the call to cls at the end of the method. Because cls refers to the Customer class, writing cls(name, email) is equivalent to writing Customer(name, email). The indirection through cls matters when inheritance is involved, because a subclass that inherits from_string will receive its own class as cls, and the method will create instances of the subclass rather than instances of the parent. This behavior makes class methods the standard way to write factory methods that respect inheritance hierarchies.
Factory methods: the primary use case for classmethod
The factory method pattern is the most common reason to write a class method, and it appears throughout the Python standard library and popular third-party packages. A factory method provides an alternative pathway for creating instances of a class, typically by accepting data in a different format than the primary constructor expects. The primary constructor, the initialization method, should be simple and direct. Factory methods handle the translation between external data formats and the internal representation the class expects.
Consider a Date class whose primary constructor accepts year, month, and day as separate integers. A from_timestamp class method might accept a Unix timestamp, perform the conversion to year, month, and day internally, and return a fully constructed Date instance. A from_iso_string class method might accept a string in the format "2026-07-10" and parse it into components. Each factory method isolates one kind of input conversion, keeping the primary constructor clean and giving callers readable, self-documenting construction paths. The caller writes Date.from_iso_string("2026-07-10") and does not need to know how the string is parsed or which calendar calculations are involved.
Factory methods also serve as documentation. When a class provides multiple class methods with descriptive names, someone reading code that uses that class can see immediately what kind of input is expected. A call to Customer.from_database_row(row) communicates more than a call to a constructor with five positional arguments whose meaning must be inferred from context. The class method name becomes part of the API, and good names make code that constructs objects read like natural language.
Class methods and class-level state
Beyond factory patterns, class methods are useful for operations that read or modify class attributes shared across all instances. If a class maintains a counter of how many instances have been created, stored as a class attribute, a class method can read that counter and return statistics without needing any particular instance to exist. This pattern appears in connection pools, caches, registries, and any situation where the class itself tracks information that spans all its instances.
Here is a simple example where a class method provides access to shared configuration that applies to every object:
class Service:
base_url = "https://api.example.com"
timeout = 30
@classmethod
def configure(cls, base_url, timeout):
cls.base_url = base_url
cls.timeout = timeoutThe configure method is a class method because it modifies class-level attributes that affect every Service object. Calling Service.configure with new values updates the shared configuration, and every existing and future Service instance sees the change the next time it reads those attributes. An instance method could not achieve this cleanly because it would operate on a specific object rather than on the class itself.
Calling class methods and inheritance behavior
Class methods can be called on the class itself or on any instance of the class, and Python passes the class as cls in both cases. Calling on the class is more explicit and is the recommended style because it makes the class-level nature of the method obvious. Writing Customer.from_string(data) tells the reader that from_string is a class-level operation that does not depend on any particular customer's data. Writing some_customer.from_string(data) is technically valid but misleading, because it suggests the method uses the instance's state when it actually ignores the instance entirely and uses the class.
The inheritance behavior of class methods is one of their most useful properties and is the reason the cls parameter exists rather than having class methods always reference their defining class by name. When a class method is called on a subclass, cls refers to the subclass, not the parent class where the method was defined. If the Customer class has a subclass called VIPCustomer, and VIPCustomer does not override from_string, calling VIPCustomer.from_string(data) still works because the inherited method receives VIPCustomer as cls and creates a VIPCustomer instance. This design lets you write factory methods once on a base class and have them automatically produce instances of whatever subclass they are called on.
The article on Python class attributes covers shared class-level data in more detail, and understanding how class attributes work helps you recognize when a class method is the right tool for operating on that shared data. The next article in this section covers static methods, the third and simplest method type, which receives no automatic parameter at all and serves as a plain function organized inside a class.
Rune AI
Key Insights
- A class method is defined with the @classmethod decorator and receives the class as its first parameter, conventionally named cls.
- Class methods can be called on the class itself or on an instance; Python passes the class as the first argument either way.
- The primary use case for class methods is factory patterns, where a method creates and returns an instance using alternate construction logic.
- Class methods can access and modify class attributes that are shared across all instances.
- In inheritance hierarchies, cls refers to the actual class the method was called on, not necessarily the class where the method was defined.
Frequently Asked Questions
What is a class method in Python and how is it different from an instance method?
When should I use a class method instead of an instance method?
Can a class method be called on an instance?
Conclusion
Class methods fill the gap between instance methods that need an object's data and static methods that need nothing at all. They give you access to the class itself through the cls parameter, enabling factory patterns, shared state management, and operations that should work consistently across an entire class hierarchy. Knowing when to reach for a class method instead of an instance method is a skill that develops with practice and with reading well-designed Python libraries.
More in this topic
Python OOP Design Best Practices
Learn the best practices for designing Python classes, from the SOLID principles adapted for Python to practical guidelines for writing maintainable object-oriented code.
Object-Oriented Programming in Python Explained
Learn what object-oriented programming means in Python, why classes and objects matter, and how OOP helps you organize larger programs into manageable, reusable pieces.
Read and Write Large Files in Python
Learn how to read and write large files in Python without running out of memory, using chunked reading, line-by-line iteration, and buffered writes.