When I build small reporting tools, I often need to create the same kind of object from different inputs. One report may come from a CSV file, another from a dictionary returned by an API, and another from values entered in the terminal.
Creating separate setup code outside the class gets messy fast. The Python classmethod() function gives the class a clean place to handle shared configuration and alternate object creation.
In this practical Python tutorial, you will learn what classmethod() does, how to use it, when it beats an instance method, and how it behaves with inheritance.
What Is the Python classmethod() Function?
The Python classmethod() function converts a method into a method that receives the class itself as its first argument.
A normal instance method receives self, which represents one object. A class method receives cls, which represents the class that called the method.
Here is the basic syntax:
class ClassName:
@classmethod
def method_name(cls, parameter):
# Code here
pass
The @classmethod line is a decorator. A decorator changes how Python handles the function below it. In this case, it tells Python to pass the class as the first argument.
You can call a class method from the class itself or from an object created from that class.
class Report:
report_type = "Monthly Sales"
@classmethod
def show_report_type(cls):
print(cls.report_type)
Report.show_report_type()
sales_report = Report()
sales_report.show_report_type()
Output:
Monthly Sales
Monthly Sales
I executed the above example code and added the screenshot below.

Both calls work. However, I usually call a class method through the class name because that makes the intent clearer.
The method uses cls.report_type because report_type belongs to the class. If you need a refresher on how classes work, read this guide on whether Python is an object-oriented language.
Python classmethod() vs Instance Method
Before you use classmethod(), you need to understand the difference between a class method and an instance method.
An instance method works with data stored in one object. A class method works with data shared by the entire class.
| Feature | Instance Method | Class Method |
|---|---|---|
| First parameter | self | cls |
| Accesses object data | Yes | No, unless an object is passed manually |
| Accesses class data | Yes | Yes |
| Called from class | No | Yes |
| Called from object | Yes | Yes |
| Common use | Update one object | Create objects or manage shared settings |
Here is a sales report example that uses both types of methods.
class SalesReport:
company_name = "Northwind Retail"
def __init__(self, manager_name, total_sales):
self.manager_name = manager_name
self.total_sales = total_sales
def show_manager_report(self):
print(f"Manager: {self.manager_name}")
print(f"Sales: ${self.total_sales:,.2f}")
@classmethod
def show_company_name(cls):
print(f"Company: {cls.company_name}")
report = SalesReport("Daniel Carter", 18450)
report.show_manager_report()
SalesReport.show_company_name()
Output:
Manager: Daniel Carter
Sales: $18,450.00
Company: Northwind Retail
I executed the above example code and added the screenshot below.

The show_manager_report() method uses self because Daniel Carter’s name and sales amount belong to one report object.
The show_company_name() method uses cls because the company name belongs to every report. This same distinction matters when you work with class and instance variables in Python.
How to Use Python classmethod()
Use a Python classmethod() when a method needs class-level information, not data from one object. The most common real-world use is creating alternate constructors.
A constructor is the method that creates an object. In Python, __init__() initializes an object after Python creates it. You can learn more about this process in this guide on the constructor in Python.
Example 1: Access a Class Variable
Let’s start with the simplest use case. A class method can access and update a class variable.
Imagine a reporting script that tracks the company-wide reporting month.
class SalesReport:
reporting_month = "January"
@classmethod
def set_reporting_month(cls, month):
cls.reporting_month = month
@classmethod
def show_reporting_month(cls):
print(f"Current reporting month: {cls.reporting_month}")
SalesReport.show_reporting_month()
SalesReport.set_reporting_month("February")
SalesReport.show_reporting_month()
Output:
Current reporting month: January
Current reporting month: February
I executed the above example code and added the screenshot below.

The set_reporting_month() method updates cls.reporting_month, so every object created from SalesReport sees the same shared value.
This works well for settings such as default tax rates, supported report formats, or a global application version.
Pro Tip: I have found that class variables work best for stable, shared settings. Do not store user-specific values in a class variable because one object can accidentally change data for every other object.
Example 2: Create an Object From a CSV Row
In automation scripts, input often arrives as text. A CSV file may contain a row like this:
Daniel Carter,Seattle,18450.75
A class method gives you a clean way to turn that string into a SalesReport object.
class SalesReport:
def __init__(self, manager_name, city, total_sales):
self.manager_name = manager_name
self.city = city
self.total_sales = total_sales
@classmethod
def from_csv_row(cls, csv_row):
manager_name, city, total_sales = csv_row.split(",")
return cls(
manager_name,
city,
float(total_sales)
)
def show_summary(self):
print(f"Manager: {self.manager_name}")
print(f"City: {self.city}")
print(f"Total Sales: ${self.total_sales:,.2f}")
csv_row = "Daniel Carter,Seattle,18450.75"
report = SalesReport.from_csv_row(csv_row)
report.show_summary()
Output:
Manager: Daniel Carter
City: Seattle
Total Sales: $18,450.75
The from_csv_row() method is an alternate constructor. It creates a SalesReport object from CSV text instead of requiring separate values.
Notice this line:
return cls(manager_name, city, float(total_sales))
Using cls() matters. It creates an object from whichever class calls the method. That becomes especially useful when you add child classes later.
If your script reads a complete file rather than one row, you may also find this guide on reading large CSV files in Python useful.
Example 3: Create an Object From a Dictionary
APIs, JSON files, and configuration files often return data as a Python dictionary. A dictionary stores values as key-value pairs.
Here is an alternate constructor that creates a report from dictionary data.
class SalesReport:
def __init__(self, manager_name, city, total_sales):
self.manager_name = manager_name
self.city = city
self.total_sales = total_sales
@classmethod
def from_dictionary(cls, report_data):
return cls(
report_data["manager_name"],
report_data["city"],
float(report_data["total_sales"])
)
def show_summary(self):
print(f"Manager: {self.manager_name}")
print(f"City: {self.city}")
print(f"Total Sales: ${self.total_sales:,.2f}")
api_report_data = {
"manager_name": "Olivia Brooks",
"city": "Austin",
"total_sales": "22980.50"
}
report = SalesReport.from_dictionary(api_report_data)
report.show_summary()
Output:
Manager: Olivia Brooks
City: Austin
Total Sales: $22,980.50
This pattern keeps conversion code inside the class. Your main script stays short and easy to read.
For more help working with key-value data, see how to initialize a dictionary in Python and check whether a key exists in a dictionary.
Python classmethod() for Alternate Constructors
The strongest use case for the Python classmethod() function is providing multiple safe ways to create the same object.
A reporting tool may receive data from a manual form, a CSV export, or a JSON response. Without class methods, you may write conversion code all over the script.
With class methods, each input format gets a clear, named constructor.
class SalesReport:
def __init__(self, manager_name, city, total_sales):
self.manager_name = manager_name
self.city = city
self.total_sales = total_sales
@classmethod
def from_csv_row(cls, csv_row):
manager_name, city, total_sales = csv_row.split(",")
return cls(manager_name, city, float(total_sales))
@classmethod
def from_dictionary(cls, report_data):
return cls(
report_data["manager_name"],
report_data["city"],
float(report_data["total_sales"])
)
@classmethod
def empty_report(cls):
return cls("Unassigned", "Unknown", 0.0)
def show_summary(self):
print(
f"{self.manager_name} | "
f"{self.city} | "
f"${self.total_sales:,.2f}"
)
csv_report = SalesReport.from_csv_row(
"Marcus Reed,Chicago,15600.25"
)
dictionary_report = SalesReport.from_dictionary(
{
"manager_name": "Grace Miller",
"city": "Denver",
"total_sales": 20340
}
)
blank_report = SalesReport.empty_report()
csv_report.show_summary()
dictionary_report.show_summary()
blank_report.show_summary()
Output:
Marcus Reed | Chicago | $15,600.25
Grace Miller | Denver | $20,340.00
Unassigned | Unknown | $0.00
Each method name explains where the input came from. That reduces guesswork when you revisit the script months later.
A class method also helps you centralize validation. For example, you can verify that a sales amount is not negative before you create the object.
class SalesReport:
def __init__(self, manager_name, city, total_sales):
self.manager_name = manager_name
self.city = city
self.total_sales = total_sales
@classmethod
def from_dictionary(cls, report_data):
total_sales = float(report_data["total_sales"])
if total_sales < 0:
raise ValueError("Total sales cannot be negative.")
return cls(
report_data["manager_name"],
report_data["city"],
total_sales
)
def show_summary(self):
print(
f"{self.manager_name} | "
f"{self.city} | "
f"${self.total_sales:,.2f}"
)
valid_report = {
"manager_name": "Ethan Walker",
"city": "Boston",
"total_sales": 19500
}
report = SalesReport.from_dictionary(valid_report)
report.show_summary()
Output:
Ethan Walker | Boston | $19,500.00
If total_sales contains -500, Python raises a ValueError. An exception is an error signal that stops normal code execution unless you handle it.
You can learn practical ways to manage errors in this article about catching multiple exceptions in Python.
classmethod() and Inheritance in Python
Inheritance lets a child class reuse behavior from a parent class. This is where cls becomes more useful than hard-coding a class name.
Suppose you have a general SalesReport class and a special RegionalSalesReport class. Both classes need to create an object from a CSV row.
class SalesReport:
def __init__(self, manager_name, city, total_sales):
self.manager_name = manager_name
self.city = city
self.total_sales = total_sales
@classmethod
def from_csv_row(cls, csv_row):
manager_name, city, total_sales = csv_row.split(",")
return cls(manager_name, city, float(total_sales))
def show_summary(self):
print(
f"{self.manager_name} | "
f"{self.city} | "
f"${self.total_sales:,.2f}"
)
class RegionalSalesReport(SalesReport):
def show_summary(self):
print(
f"Regional Report: {self.manager_name} | "
f"{self.city} | "
f"${self.total_sales:,.2f}"
)
regional_report = RegionalSalesReport.from_csv_row(
"Sophia Turner,Miami,27800"
)
regional_report.show_summary()
print(type(regional_report).__name__)
Output:
Regional Report: Sophia Turner | Miami | $27,800.00
RegionalSalesReport
The inherited from_csv_row() method returns a RegionalSalesReport object because it uses cls().
If the method used SalesReport() instead, Python would create the parent object and lose the child class behavior.
For a deeper look at inheritance design, review Python composition vs inheritance and Python method resolution order.
Pro Tip: In real projects, I use
cls()inside factory-style class methods almost every time. It costs nothing, supports inheritance properly, and prevents subtle bugs when another developer extends the class later.
classmethod() vs staticmethod() in Python
A staticmethod is another type of method that lives inside a class. Unlike a class method, it does not receive self or cls automatically.
Use a static method when the function relates to the class but does not need class-level or object-level data.
class SalesReport:
company_name = "Northwind Retail"
def __init__(self, manager_name, total_sales):
self.manager_name = manager_name
self.total_sales = total_sales
@classmethod
def company_message(cls):
print(f"Welcome to {cls.company_name}")
@staticmethod
def format_currency(amount):
return f"${amount:,.2f}"
SalesReport.company_message()
formatted_sales = SalesReport.format_currency(18450.5)
print(formatted_sales)
Output:
Welcome to Northwind Retail
$18,450.50
The company_message() method needs cls.company_name, so it must be a class method.
The format_currency() method only formats the provided number. It does not need data from an object or the class, so a static method fits better.
For a more detailed comparison, read Python class method vs static method.
Things to Keep in Mind
- Use
cls, not a hard-coded class name: Returncls(...)from alternate constructors so child classes also create the right object type. - Keep class methods focused: Use them for shared settings, validation, and object creation. Put object-specific work in instance methods.
- Validate external input: Convert and check CSV, JSON, or API values before creating an object. This prevents bad data from spreading through your automation script.
- Avoid mutable class variables: Do not use a shared list or dictionary for object-specific data unless every object should truly share it.
- Choose static methods carefully: Use
@staticmethodonly when the method does not needselforcls. - Use descriptive constructor names: Names such as
from_csv_row(),from_dictionary(), andfrom_api_response()explain the input source immediately.
Frequently Asked Questions
What does classmethod() do in Python?
The classmethod() function turns a regular method into a class method. Python passes the class as the first argument, which developers usually name cls. This lets the method access class variables and create objects through cls().
What is the difference between cls and self in Python?
self refers to one object created from a class. cls refers to the class itself. Use self for object-specific values and cls for shared class values or alternate constructors.
Can I call a class method using an object?
Yes, Python lets you call a class method through an object. For example, report.show_company_name() works. I recommend calling it through the class name, such as SalesReport.show_company_name(), because it makes the shared behavior obvious.
When should I use @classmethod in Python?
Use @classmethod when you need shared class configuration or more than one way to create an object. It works especially well for parsing CSV rows, dictionaries, JSON data, environment values, or API responses.
Why should I use cls() instead of the class name?
cls() creates an object from the class that called the method. This supports inheritance automatically. A hard-coded class name always creates the parent class object, even when a child class calls the method.
Can a class method access instance variables?
Not directly. A class method has no specific object, so it cannot access values such as self.manager_name. You can pass an object into the method, but an instance method is usually the cleaner choice.
The Python classmethod() function helps you keep shared class logic and alternate object creation in one clear place. Start with a simple from_dictionary() or from_csv_row() method, then add validation and inheritance support as your script grows. I hope you found this article helpful.
You May Also Like
- How to define a function in Python
- How to use Python functions with optional arguments
- Python dataclass vs normal class
- How to build a simple OOP project in Python
- Python property decorator guide

Bijay Kumar is an experienced Python and AI professional who enjoys helping developers learn modern technologies through practical tutorials and examples. His expertise includes Python development, Machine Learning, Artificial Intelligence, automation, and data analysis using libraries like Pandas, NumPy, TensorFlow, Matplotlib, SciPy, and Scikit-Learn. At PythonGuides.com, he shares in-depth guides designed for both beginners and experienced developers. More about us.