Python classmethod() Function: Complete Guide With Examples

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.

Python classmethod() Function

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.

FeatureInstance MethodClass Method
First parameterselfcls
Accesses object dataYesNo, unless an object is passed manually
Accesses class dataYesYes
Called from classNoYes
Called from objectYesYes
Common useUpdate one objectCreate 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.

classmethod() Function Python

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.

classmethod() Function in Python

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 P