Python classmethod() Function: How to Use It With Examples

A billing script I worked on had to build invoices from three places: a CSV export, a JSON API and a web form. Cramming all three into one __init__ got ugly fast, and that’s exactly where Python’s classmethod() function earns its keep.

Your first instinct might be a plain helper like make_invoice(row). It works until someone subclasses Invoice: the helper still hard-codes the parent class, so the subclass quietly gets the wrong type back.

Quick answer: put @classmethod above a method and Python passes the class itself as the first argument, cls.

class Invoice:
    @classmethod
    def from_csv_row(cls, row):
        number, total = row.split(",")
        return cls(number, float(total))

In this tutorial, I’ll walk through the Python classmethod() function with one running Invoice class, from the decorator to subclasses and the mistakes I see most.

My test runs used Python 3.12.5, plus Python 3.14.8 for one behavior that changed in 3.13.

What does the Python classmethod() function do?

classmethod() is a built-in that turns a function into a class method. It gets the class, not an instance, as its first argument, so you can read and change data every object shares.

Here the Invoice class stores the sales tax rate once. If you’re new to the difference between class and instance variables, this is the class-variable side of it:

class Invoice:
    tax_rate = 0.0825            # Austin, TX sales tax

    def __init__(self, number, customer, subtotal):
        self.number = number
        self.customer = customer
        self.subtotal = subtotal

    @classmethod
    def set_tax_rate(cls, rate):
        cls.tax_rate = rate
        print(f"{cls.__name__}.tax_rate is now {rate:.2%}")

    def total(self):
        return round(self.subtotal * (1 + self.tax_rate), 2)


inv = Invoice("INV-1042", "Emily Carter", 1250.00)
print(f"Total at 8.25%: ${inv.total():,.2f}")

Invoice.set_tax_rate(0.0625)     # call it on the class
print(f"Total at 6.25%: ${inv.total():,.2f}")

inv.set_tax_rate(0.07)           # on an instance, cls is still Invoice
print(Invoice.tax_rate, "tax_rate" in vars(inv))

Output:

Total at 8.25%: $1,353.12
Invoice.tax_rate is now 6.25%
Total at 6.25%: $1,328.12
Invoice.tax_rate is now 7.00%
0.07 False
VS Code running a Python classmethod that changes the tax_rate class variable for every Invoice
Changing the rate through the class method updates the total of an invoice that already existed.

The $1,250.00 invoice goes from $1,353.12 to $1,328.12 without touching the object. Calling it on an instance still changes the class, so tax_rate isn’t in vars(inv).

Using classmethod() as a function instead of @classmethod

Before decorators arrived in Python 2.4, you wrapped the function by hand. It still works, and it’s handy for adding methods at runtime:

class Invoice:
    tax_rate = 0.0825

    def label(cls):
        return f"{cls.__name__} at {cls.tax_rate:.2%} tax"

    label = classmethod(label)   # same as putting @classmethod on top


print(type(Invoice.__dict__["label"]))
print(Invoice.label)
print(Invoice.label())


def currency(cls):
    return f"{cls.__name__} amounts are in USD"


Invoice.currency = classmethod(currency)    # add one at runtime
print(Invoice.currency())

Output:

<class 'classmethod'>
<bound method Invoice.label of <class '__main__.Invoice'>>
Invoice at 8.25% tax
Invoice amounts are in USD
VS Code output of the classmethod() function call showing a classmethod object and a bound method of the class
Inside the class dictionary it’s a classmethod object; looked up on the class, it’s a method bound to the class.

The output says bound method ... of <class '__main__.Invoice'>: it’s bound to the class itself. I’d still use @classmethod in everyday code.

How do you write alternate constructors with classmethod?

This is the job I use class methods for most. A regular constructor in Python takes one fixed set of arguments; each class method can take a different input and return cls(...):

from datetime import date


class Invoice:
    def __init__(self, number, customer, subtotal, issued):
        self.number = number
        self.customer = customer
        self.subtotal = subtotal
        self.issued = issued

    @classmethod
    def from_csv_row(cls, row):
        number, customer, subtotal, issued = row.split(",")
        return cls(number, customer, float(subtotal),
                   date.fromisoformat(issued))

    @classmethod
    def from_dict(cls, data):
        return cls(data["id"], data["name"], data["amount"],
                   date.fromisoformat(data["date"]))

    def __repr__(self):
        return f"{self.number} {self.customer} ${self.subtotal:,.2f}"


rows = ["INV-1042,Emily Carter,1250.00,2026-03-15",
        "INV-1043,James Miller,489.99,2026-03-16"]
for row in rows:
    print(Invoice.from_csv_row(row))

api = {"id": "INV-1044", "name": "Olivia Brooks",
       "amount": 2310.5, "date": "2026-03-18"}
print(Invoice.from_dict(api))

Output:

INV-1042 Emily Carter $1,250.00
INV-1043 James Miller $489.99
INV-1044 Olivia Brooks $2,310.50
VS Code output of Python classmethod alternate constructors from_csv_row and from_dict building invoices
Two invoices come from CSV text and one from an API dictionary, all through class methods.

You get three ready Invoice objects, the largest at $2,310.50 for Olivia Brooks. That’s the same pattern as dict.fromkeys().

Since Python has no real overloading, this is the clean answer to constructor overloading in Python. For picking a class at runtime, see the factory pattern in Python.

Why does a classmethod return the right subclass?

Because cls is whatever class you called it on. Here’s a RushInvoice subclass with a $35.00 fee, and a static method that hard-codes the parent:

class Invoice:
    def __init__(self, number, subtotal):
        self.number = number
        self.subtotal = subtotal

    @classmethod
    def from_csv_row(cls, row):
        number, subtotal = row.split(",")
        return cls(number, float(subtotal))

    @staticmethod
    def parse(row):
        number, subtotal = row.split(",")
        return Invoice(number, float(subtotal))   # class hard-coded

    def total(self):
        return self.subtotal


class RushInvoice(Invoice):
    rush_fee = 35.00

    def total(self):
        return self.subtotal + self.rush_fee


a = RushInvoice.from_csv_row("INV-2001,400.00")
b = RushInvoice.parse("INV-2002,400.00")
print(f"classmethod:  {type(a).__name__:<12} ${a.total():,.2f}")
print(f"staticmethod: {type(b).__name__:<12} ${b.total():,.2f}")

Output:

classmethod:  RushInvoice  $435.00
staticmethod: Invoice      $400.00
VS Code output comparing a classmethod and a staticmethod constructor called on a Python subclass
The class method builds a RushInvoice; the static method builds a plain Invoice and loses the rush fee.

You only get a RushInvoice from the class method, so its total is $435.00 instead of $400.00. Python finds the method through your class’s method resolution order, but cls stays the class you called.

classmethod vs staticmethod vs instance methods

Method typeFirst argumentCan useTypical job
Instance methodselfObject + classWork on one invoice
@classmethodclsThe classAlternate constructors
@staticmethodNothingIts argumentsHelpers

My rule: if it needs the class, use a class method; if it needs nothing, use a static method. I go deeper in Python class method vs static method.

Common errors with classmethod and how to fix them

Forgetting the decorator. Without @classmethod, cls is just a normal parameter, so Invoice.from_number("INV-3001") fails with TypeError: Invoice.from_number() missing 1 required positional argument: 'number'.

Counting with cls. cls.created += 1 on a subclass creates a new attribute there instead of updating the parent:

class Invoice:
    created = 0

    @classmethod
    def register(cls):
        cls.created += 1


class RushInvoice(Invoice):
    pass


Invoice.register()
RushInvoice.register()
RushInvoice.register()
print(Invoice.created, RushInvoice.created)
print("created" in vars(RushInvoice))

Output:

1 3
True

Three invoices registered, yet Invoice.created is still 1 while the subclass counted on to 3 by itself. For one shared total, write Invoice.created += 1.

Stacking @classmethod on @property. Python 3.9 allowed this, 3.11 deprecated it and 3.13 removed it. Here’s what you get running one file on both:

import sys


class Invoice:
    @classmethod
    @property
    def kind(cls):
        return cls.__name__.upper()


print("Python", sys.version.split()[0])
print(repr(Invoice.kind))
VS Code output on Python 3.12 and 3.14 showing @classmethod stacked on @property returning a string, then a bound method
On Python 3.12 the stacked decorators still return ‘INVOICE’; on 3.14 you get a bound method object instead.

If you need a computed class-level value, call a plain class method (Invoice.kind()) or use a class variable. Regular instance properties are covered in my Python property decorator guide.

Ready for more object-oriented Python? Try these:

Frequently asked questions

What is the classmethod() function in Python?

It’s a built-in that turns a function into a method that receives the class (cls) instead of an instance.

Should I use classmethod() or @classmethod?

Use @classmethod in normal code. The classmethod(func) call does the same thing and you’ll mostly need it when adding methods at runtime.

Can I call a class method from an instance?

Yes. cls is still the instance’s class, so inv.set_tax_rate(0.07) changes the rate for every invoice.

Why is it called cls and not self?

It’s only a convention, but it tells you the first parameter holds the class.

Can a class method access instance variables?

Not directly, because it doesn’t get an instance. It can create one with cls(...), though.

Where is classmethod() documented?

See classmethod() in the official Python docs.