Sub topic 5
Classmethods and Staticmethods
This chapter assumes you can write a basic class with __init__ and instance methods, and that you know the difference between instance attributes and class attributes. You should also be comfortable with decorators as a syntax (@name above a function), though you do not need to write one.
By the end you will be able to choose between an instance method, a classmethod, and a staticmethod, and to write alternative constructors that work correctly with subclasses.
Three kinds of methods
Every method you define in a class body is a plain function stored as a class attribute. What differs is what Python passes as the first argument when you call it.
| Kind | Decorator | First argument | Can read instance state | Can read class state |
|---|---|---|---|---|
| Instance method | none | the instance (`self`) | yes | yes, through `type(self)` |
| Classmethod | `@classmethod` | the class (`cls`) | no | yes |
| Staticmethod | `@staticmethod` | nothing extra | no | no (unless you name the class) |
The names self and cls are conventions. Python does not treat them specially, but every tool and reader expects them.
Classmethods
A classmethod receives the class itself as its first argument. This happens whether you call it on the class or on an instance. In the second case Python uses type(instance) and ignores the instance.
The most common use is an alternative constructor: a method that builds an instance from some input other than the arguments of __init__.
class Pizza:
def __init__(self, toppings):
self.toppings = list(toppings)
@classmethod
def margherita(cls):
return cls(["mozzarella", "basil"])
@staticmethod
def is_valid_topping(name):
return name.isalpha()
p = Pizza.margherita()
print(p.toppings) # ['mozzarella', 'basil']
print(Pizza.is_valid_topping("ham")) # Truemargherita calls cls([...]) and not Pizza([...]). That choice matters as soon as subclasses exist, as the next section shows.
Why `cls` and not the class name
If you hard-code the class name inside a classmethod, every subclass gets an instance of the parent.
class Pizza:
def __init__(self, toppings):
self.toppings = list(toppings)
@classmethod
def margherita(cls):
return cls(["mozzarella", "basil"])
@classmethod
def margherita_hardcoded(cls):
return Pizza(["mozzarella", "basil"]) # ignores cls
class StuffedCrustPizza(Pizza):
pass
print(type(StuffedCrustPizza.margherita()).__name__) # StuffedCrustPizza
print(type(StuffedCrustPizza.margherita_hardcoded()).__name__) # PizzaThe first call respects the subclass. The second silently returns the wrong type, and any methods the subclass added are missing. Using cls is the whole reason classmethods exist as a separate feature.
Parsing constructors
Another typical use is building objects from external formats. The __init__ method stays simple and takes already-parsed values. The classmethods handle conversion.
from datetime import date
class Event:
def __init__(self, title, day):
self.title = title
self.day = day
@classmethod
def from_string(cls, text):
title, _, iso_day = text.partition("@")
return cls(title.strip(), date.fromisoformat(iso_day.strip()))
def __repr__(self):
return f"{type(self).__name__}({self.title!r}, {self.day!r})"
print(Event.from_string("Launch @ 2026-12-01"))
# Event('Launch', datetime.date(2026, 12, 1))The standard library uses the same pattern: dict.fromkeys, datetime.date.today, and datetime.date.fromisoformat are all classmethods.
Classmethods and class state
A classmethod can read and update class attributes. Use cls.attribute = ... to rebind the attribute on that class.
class Counter:
created = 0
def __init__(self):
type(self).created += 1
@classmethod
def how_many(cls):
return cls.created
Counter()
Counter()
print(Counter.how_many()) # 2There is a subtlety with inheritance. Assignment through cls creates or updates the attribute on the exact class that cls refers to.
class SubCounter(Counter):
pass
SubCounter()
print(SubCounter.created) # 3
print(Counter.created) # 2The first SubCounter() runs type(self).created += 1. This reads created from Counter (value 2), adds one, and stores 3 on SubCounter itself. The parent keeps 2. If you want one count shared by the whole hierarchy, write Counter.created += 1 explicitly. If you want one count per subclass, use cls or type(self). Decide deliberately, because both behaviors are easy to produce by accident.
Staticmethods
A staticmethod receives no automatic first argument. It behaves like a module-level function that happens to live in the class namespace.
class Temperature:
@staticmethod
def celsius_to_fahrenheit(c):
return c * 9 / 5 + 32
print(Temperature.celsius_to_fahrenheit(100)) # 212.0
print(Temperature().celsius_to_fahrenheit(0)) # 32.0You can call it on the class or on an instance, and the result is the same.
Use a staticmethod when a function is closely tied to a class conceptually but needs neither the instance nor the class. Validation helpers, small converters, and parsing utilities are typical. If the function is useful on its own and not tied to the class, a module-level function is usually simpler and more Pythonic. Python is not Java, and there is no rule that all functions must live inside classes.
What a staticmethod is for in practice
A staticmethod does two things a module-level function does not:
- It appears in the class's namespace, so it is discoverable through the class and its documentation.
- Subclasses can override it, and callers that go through
self.helper(...)orcls.helper(...)pick up the override.
class Report:
@staticmethod
def format_number(n):
return f"{n:,}"
def render(self, values):
return ", ".join(self.format_number(v) for v in values)
class PlainReport(Report):
@staticmethod
def format_number(n):
return str(n)
print(Report().render([1000, 2000000])) # 1,000, 2,000,000
print(PlainReport().render([1000, 2000000])) # 1000, 2000000If render had called a module-level function, subclasses could not change the formatting without overriding render itself.
How the decorators work
You do not need this to use the decorators, but it explains the behavior above and several error messages.
A function in a class body is a descriptor. When you access it through an instance, Python calls its __get__ method, which returns a bound method with the instance already filled in as the first argument. classmethod and staticmethod are objects that customize this step:
classmethod.__get__returns a method bound to the class, whether you access it through the class or an instance.staticmethod.__get__returns the underlying function unchanged.
You can see the difference by inspecting the results.
class Demo:
def instance(self):
return "instance"
@classmethod
def klass(cls):
return "class"
@staticmethod
def static():
return "static"
d = Demo()
print(d.instance) # <bound method Demo.instance of <__main__.Demo object at 0x...>>
print(d.klass) # <bound method Demo.klass of <class '__main__.Demo'>>
print(d.static) # <function Demo.static at 0x...>
print(Demo.instance(d)) # instanceThe last line shows that an instance method accessed through the class is just a function. You pass the instance yourself.
Common errors
Forgetting the decorator
class Broken:
def make():
return "made"
try:
Broken().make()
except TypeError as exc:
print(exc) # Broken.make() takes 0 positional arguments but 1 was givenWithout @staticmethod, Python binds the instance and passes it as an argument. The function accepts none, so you get a TypeError. The message counts the instance, which makes it look like you passed one argument you did not write. Add @staticmethod, or add self if you meant an instance method.
Using `self` in a staticmethod or `cls` in an instance method
A staticmethod has no self. If you write def f(self) under @staticmethod, the first real argument you pass fills self, which is almost never what you intended. Likewise, an instance method that names its first parameter cls still receives the instance. The name does not change the behavior.
Hard-coding the class
As shown earlier, return Pizza(...) in a classmethod breaks subclasses. Always use cls(...).
Alternative constructors with incompatible `__init__`
cls(...) calls the subclass's __init__. If a subclass changes the signature of __init__, parent classmethods that call cls(...) with the old arguments will fail. Either keep subclass signatures compatible, or override the classmethod as well.
Stacking decorators in the wrong order
Since Python 3.9, a classmethod can wrap other descriptors such as property, but this chaining was deprecated in 3.11 and removed in 3.13. Do not rely on it. Use a regular @classmethod and a separate @property where each is needed.
Choosing between the three
Ask what the method needs.
- Does it read or change data on a particular object? Use an instance method.
- Does it need the class, for example to construct an instance or to read a class attribute, and should it respect subclasses? Use a classmethod.
- Does it need neither? Consider a module-level function first. Use a staticmethod if grouping it in the class helps readers or if you want subclasses to override it.
A quick test: if you would be tempted to write the class name inside the method body, you likely want a classmethod and cls.
Summary
- Instance methods receive the instance, classmethods receive the class, and staticmethods receive nothing automatically.
- Classmethods are the standard way to write alternative constructors. Always build the result with
cls(...)so subclasses get their own type. - Assigning through
clsortype(self)sets the attribute on that specific class, which can split counters between a parent and its subclasses. - Staticmethods are plain functions in a class namespace. Prefer a module-level function unless grouping or overriding is useful.
- Forgetting the decorator produces a confusing
TypeErrorabout argument counts.
Exercise
A class Config has @classmethod def from_env(cls): return Config(read_environment()). A subclass TestConfig(Config) calls TestConfig.from_env(). What type is returned, and how do you fix the method?
Show answer
It returns a plain Config, because the method hard-codes the class name and ignores cls. Change the body to return cls(read_environment()) so that TestConfig.from_env() returns a TestConfig.
Exercise
Given class A: count = 0, class B(A): pass, and __init__ in A that runs type(self).count += 1, what are A.count and B.count after creating one A and then two B instances?
Show answer
A.count is 1 and B.count is 2. The first B() reads 1 from A, adds one, and stores 2 on B. The second B() reads 2 from B and stores 3 on B, so B.count is 3, not 2. Correct result: A.count == 1, B.count == 3. To share one counter, use A.count += 1.
Exercise
Write a classmethod from_pair on a class Point whose __init__ takes x and y, so that Point.from_pair("3,4") returns Point(3, 4) with integer coordinates.
Show answer
@classmethod
def from_pair(cls, text):
x, y = text.split(",")
return cls(int(x), int(y))
The method splits the string on the comma, converts each part to int, and builds the instance with cls so subclasses of Point return their own type.