In Python, a class method is a special type of method that operates on the class itself rather than individual objects. It is defined using the @classmethod decorator and receives the class reference (cls) as its first parameter.
Class methods are widely used for factory methods, class-level operations, and alternative constructors. Understanding how @classmethod works helps developers write more structured and reusable object-oriented Python code.
Python ClassMethod Quick Reference
| Feature | Class Method | Instance Method | Static Method |
|---|---|---|---|
| Decorator | @classmethod | None | @staticmethod |
| First Parameter | cls | self | None |
| Access Class Variables | Yes | Yes | No |
| Access Instance Variables | No | Yes | No |
| Callable from Class | Yes | No | Yes |
| Callable from Instance | Yes | Yes | Yes |
| Common Use Cases | Factory methods, alternative constructors | Object behavior | Utility functions |
What is a Class Method in Python
A class method in Python is a method that is bound to the class instead of an instance of the class. It is defined using the @classmethod decorator and receives the class itself as the first argument, which is conventionally named cls.
Class methods allow you to access or modify class-level variables and perform operations that affect the entire class rather than individual objects.
Understanding the purpose of class methods
The primary purpose of a class method is to work with class-level data that is shared across all instances of the class.
Typical uses include:
- Managing shared class variables
- Creating alternative constructors
- Performing operations related to the class itself
Example:
class Counter:
total = 0
@classmethod
def increment(cls):
cls.total += 1Calling the method:
Counter.increment()
In this example, the class method modifies a class variable shared by all objects.
When a class method should be used
You should use a class method when the logic involves class-level operations instead of instance-level behavior.
Common scenarios include:
- Creating factory methods
- Managing shared counters
- Updating class configuration
- Implementing alternative constructors
Example of a factory method:
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
@classmethod
def from_string(cls, data):
brand, model = data.split("-")
return cls(brand, model)Usage:
car = Car.from_string("Toyota-Camry")
Key characteristics of class methods
Class methods have several important characteristics:
| Characteristic | Description |
|---|---|
| Decorator | Defined using @classmethod |
| First parameter | Receives the class (cls) |
| Class access | Can access and modify class variables |
| Instance access | Cannot directly access instance variables |
| Invocation | Can be called from both class and instance |
Example:
class Example:
value = 10
@classmethod
def show_value(cls):
print(cls.value)Calling:
Example.show_value()
Python ClassMethod Syntax
Basic structure of the @classmethod decorator
A class method is declared using the @classmethod decorator placed above the method definition.
The basic syntax looks like this:
class ClassName:
@classmethod
def method_name(cls, arguments):
passHere:
@classmethodtells Python the method belongs to the classclsrepresents the class itself
Defining a class method inside a Python class
Example of defining a simple class method:
class User:
total_users = 0
@classmethod
def add_user(cls):
cls.total_users += 1Each time the method runs, it updates the class variable shared by all objects.
Calling a class method from the class
A class method can be called directly using the class name.
Example:
class Example:
@classmethod
def greet(cls):
print("Hello from class method")Calling the method:
Example.greet()
Calling a class method from an instance
Class methods can also be called from an instance of the class.
Example:
obj = Example()
obj.greet()Even when called from an instance, Python automatically passes the class as the first argument (cls).
Understanding the cls Parameter in Python
The cls parameter refers to the class itself, similar to how self refers to the instance.
It allows class methods to interact with class attributes and other class methods.
What does cls represent
The cls parameter represents the class object that the method belongs to.
Example:
class Example:
@classmethod
def show_class(cls):
print(cls)Calling:
Example.show_class()
Output will display the class reference.
Difference between cls and self
Understanding the difference between cls and self is essential when working with Python classes.
| Parameter | Used In | Represents |
|---|---|---|
self | Instance methods | The object instance |
cls | Class methods | The class itself |
Example:
class Demo:
def instance_method(self):
print("Instance method")
@classmethod
def class_method(cls):
print("Class method")Accessing class variables using cls
Class methods can access class variables through cls.
Example:
class Product:
tax = 5
@classmethod
def get_tax(cls):
return cls.taxCalling:
Product.get_tax()
Modifying class-level data using cls
Class methods can also update shared class variables.
Example:
class Settings:
mode = "development"
@classmethod
def change_mode(cls, new_mode):
cls.mode = new_modeUsage:
Settings.change_mode("production")
Python ClassMethod vs Instance Method vs Static Method
In Python, methods defined inside a class can behave differently depending on how they interact with the class or instance. The three main types are:
- Instance methods
- Class methods
- Static methods
Instance method vs class method
An instance method operates on individual objects of a class, while a class method operates on the class itself.
| Feature | Instance Method | Class Method |
|---|---|---|
| First parameter | self | cls |
| Access instance variables | Yes | No |
| Access class variables | Yes | Yes |
| Called from class | No | Yes |
| Called from instance | Yes | Yes |
Example:
class Example:
class_value = 10
def instance_method(self):
print("Instance method")
@classmethod
def class_method(cls):
print(cls.class_value)Usage:
obj = Example()
obj.instance_method()
Example.class_method()
Class method vs static method
A class method receives the class (cls) as its first argument, while a static method does not receive either cls or self.
Static methods behave like normal functions placed inside a class for organization.
| Feature | Class Method | Static Method |
|---|---|---|
| Decorator | @classmethod | @staticmethod |
| First parameter | cls | None |
| Access class variables | Yes | No |
| Access instance variables | No | No |
| Typical use | Class operations | Utility functions |
Example:
class Example:
value = 10
@classmethod
def show_value(cls):
print(cls.value)
@staticmethod
def greet():
print("Hello from static method")Usage:
Example.show_value()
Example.greet()
When to use each method type
Choosing the correct method type depends on what data the method needs to work with.
Use instance methods when:
- The method works with instance attributes
- Each object behaves differently
Use class methods when:
- The method modifies class-level data
- You want to implement factory methods
Use static methods when:
- The function is related to the class but does not require class or instance data
Example:
class Calculator:
@staticmethod
def add(a, b):
return a + bPractical comparison examples
Example demonstrating all three method types:
class Demo:
class_value = 5
def instance_method(self):
print("Instance method called")
@classmethod
def class_method(cls):
print("Class value:", cls.class_value)
@staticmethod
def static_method():
print("Static method called")Usage:
obj = Demo()
obj.instance_method()
Demo.class_method()
Demo.static_method()
Creating Alternative Constructors
One of the most common uses of class methods is creating alternative constructors, also known as factory methods. These methods allow objects to be created using different input formats.
Creating objects from string data
Sometimes object data may come as a string and needs to be converted into object attributes.
Example:
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
@classmethod
def from_string(cls, data):
brand, model = data.split("-")
return cls(brand, model)Usage:
car = Car.from_string("Toyota-Camry")
Creating objects from configuration files
Class methods can also create objects using configuration values.
Example:
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"])Usage:
config = {"host": "localhost", "port": 3306}
db = Database.from_config(config)
Creating objects from JSON data
Applications often receive data in JSON format, which can be converted into objects using class methods.
Example:
import json
class User:
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"])Usage:
user = User.from_json('{"name": "John", "age": 30}')
Using class methods as factory methods
Factory methods provide multiple ways to create objects without directly calling the constructor.
Example:
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
@classmethod
def from_fahrenheit(cls, fahrenheit):
celsius = (fahrenheit - 32) * 5 / 9
return cls(celsius)Usage:
temp = Temperature.from_fahrenheit(86)
Managing Class-Level Data
Maintaining shared counters across instances
A class variable can be used to track how many objects have been created.
Example:
class Employee:
total_employees = 0
def __init__(self):
Employee.increment()
@classmethod
def increment(cls):
cls.total_employees += 1Usage:
emp1 = Employee()
emp2 = Employee()
print(Employee.total_employees)
Updating configuration variables
Class methods can update configuration values that affect all instances.
Example:
class Settings:
mode = "development"
@classmethod
def change_mode(cls, new_mode):
cls.mode = new_modeUsage:
Settings.change_mode("production")
Tracking object creation using class methods
Class methods can maintain statistics about object creation.
Example:
class Session:
active_sessions = 0
def __init__(self):
Session.start_session()
@classmethod
def start_session(cls):
cls.active_sessions += 1Usage:
s1 = Session()
s2 = Session()
print(Session.active_sessions)
Using Class Methods with Inheritance
Class methods work well with inheritance because the cls parameter always refers to the current class that calls the method, not necessarily the class where the method was defined.
This makes class methods very flexible when building class hierarchies.
Overriding class methods in subclasses
A subclass can override a class method from its parent class to change or extend its behavior.
Example:
class Animal:
@classmethod
def describe(cls):
print("This is a generic animal")
class Dog(Animal):
@classmethod
def describe(cls):
print("This is a dog")Usage:
Dog.describe()
In this case, the subclass replaces the parent implementation.
Calling parent class methods using super()
Sometimes you may want to extend the parent class behavior instead of replacing it completely. This can be done using super().
Example:
class Animal:
@classmethod
def describe(cls):
print("Animal class")
class Dog(Animal):
@classmethod
def describe(cls):
print("Dog class")
super().describe()Usage:
Dog.describe()
Output:
Dog class
Animal class
Preserving functionality in inherited classes
Using super() allows subclasses to reuse existing logic while adding their own functionality.
Example:
class Vehicle:
category = "Transport"
@classmethod
def info(cls):
return f"Category: {cls.category}"
class Car(Vehicle):
category = "Car"
@classmethod
def info(cls):
base_info = super().info()
return f"{base_info} -> Type: {cls.category}"Usage:
print(Car.info())
Advanced Uses of Python Class Methods
Using class methods in design patterns
Class methods are frequently used to implement factory design patterns where objects can be created in multiple ways.
Example:
class User:
def __init__(self, username):
self.username = username
@classmethod
def from_email(cls, email):
username = email.split("@")[0]
return cls(username)Usage:
user = User.from_email("john@example.com")
Dynamically assigning class methods
Python allows methods to be assigned dynamically to classes at runtime.
Example:
class Example:
pass
def show_class_name(cls):
print(cls.__name__)
Example.show_name = classmethod(show_class_name)Usage:
Example.show_name()
Using class methods with metaclasses
Metaclasses control how classes behave in Python. Class methods can also be defined inside metaclasses to influence class behavior.
Example:
class Meta(type):
@classmethod
def describe(cls):
print("This is a metaclass method")
class MyClass(metaclass=Meta):
passUsage:
MyClass.describe()
This allows functionality to be shared across all classes using the same metaclass.
Common Mistakes When Using ClassMethod
Forgetting the @classmethod decorator
If the decorator is missing, Python treats the method as an instance method, which can cause errors.
Incorrect example:
class Example:
def show(cls):
print("This is incorrect")Correct version:
class Example:
@classmethod
def show(cls):
print("This is a class method")Confusing cls with self
A common mistake is mixing up the meaning of cls and self.
| Parameter | Used in | Represents |
|---|---|---|
self | Instance methods | The object instance |
cls | Class methods | The class itself |
Example:
class Demo:
@classmethod
def show_class(cls):
print(cls)Trying to access instance variables from class methods
Class methods cannot directly access instance variables because they operate at the class level.
Incorrect example:
class Example:
def __init__(self):
self.value = 10
@classmethod
def show(cls):
print(self.value)This will produce an error because self is not available.
Misusing class methods as utility functions
Sometimes developers use class methods for tasks that should be implemented as static methods or standalone functions.
Example of a better approach:
class MathUtils:
@staticmethod
def add(a, b):
return a + bStatic methods are better when the function does not require access to class or instance data.
Frequently Asked Questions
1. What is a classmethod in Python?
A classmethod in Python is a method that is bound to the class rather than an instance. It receives the class as the first parameter (usually named cls) and is defined using the @classmethod decorator.2. What does cls mean in Python?
The cls parameter represents the class itself in a class method. It allows access to class variables and other class methods.3. How is classmethod different from staticmethod?
A classmethod receives the class (cls) as its first parameter and can modify class state, while a staticmethod does not receive cls or self and behaves like a normal function inside the class.4. When should you use classmethod in Python?
Class methods are commonly used for factory methods, managing class-level data, and implementing alternative constructors.5. Can a classmethod be called from an instance?
Yes, a classmethod can be called from both the class itself and from instances of that class.Summary
Python class methods provide a structured way to define behavior that operates on the class itself rather than individual instances. By using the @classmethod decorator and the cls parameter, developers can access and modify class-level attributes, implement factory methods, and build flexible object-oriented designs.
Throughout this guide, we explored how class methods differ from instance methods and static methods, how they interact with inheritance, and how they are commonly used in real-world scenarios such as creating alternative constructors and managing shared class data.
Understanding when to use instance methods, class methods, and static methods helps developers write cleaner and more maintainable Python code. Class methods are especially useful when working with class-level state, object creation logic, and reusable class behaviors.
Official Documentation
For more details and advanced concepts related to Python class methods, refer to the official Python documentation:


