Python @staticmethod vs @classmethod Explained
What you’ll learn
Section titled “What you’ll learn”- What instance methods, class methods and static methods receive, and how to choose between them.
- How
@classmethodalternative constructors keep working for subclasses. - What the decorators actually store in the class, explained through the descriptor protocol.
- Pitfalls with class-level state, chained decorators and
functools.partialin Python 3.14. - How to argue the choice in a design review or interview.
Summary
Section titled “Summary”A plain function defined in a class becomes an instance method: accessed through an instance, it binds and receives the instance as self. @classmethod makes the method receive the class (cls) instead, whether it is called on the class or on an instance, and the class is the one the method was accessed through, which may be a subclass. @staticmethod receives nothing implicitly; it is a plain function that lives in the class namespace. Both decorators date from Python 2.2 and are current in Python 3.14.
The problem it solves
Section titled “The problem it solves”Code that belongs with a class but does not need an instance is common: parsing a row into an object, building a test fixture, validating an input. Written as module-level functions, these helpers scatter the API and hard-code the class they build. In the OrdersPortal app, a function that builds an Order from a CSV row always returns an Order, even when the caller wanted a PriorityOrder.
The samples on this page are plain scripts: save each as a .py file and run it with python3 file.py. They were run on CPython 3.14.6 and the output shown is from that run.
from datetime import date
# Before: a module-level helper hard-codes the class it builds.class OrderV1: def __init__(self, order_id, placed_on, currency): self.order_id, self.placed_on, self.currency = order_id, placed_on, currency
def order_from_row(row): # always returns OrderV1 return OrderV1(row["id"], date.fromisoformat(row["placed_on"]), row["currency"])
class PriorityOrderV1(OrderV1): pass
print(type(order_from_row({"id": "ORD-1", "placed_on": "2026-11-02", "currency": "EUR"})).__name__)
# After: one class, three kinds of method.class Order: SUPPORTED_CURRENCIES = {"EUR", "USD", "GBP"}
def __init__(self, order_id, placed_on, currency): if not self.is_supported_currency(currency): raise ValueError(f"unsupported currency {currency!r}") self.order_id, self.placed_on, self.currency = order_id, placed_on, currency
def describe(self): # instance method: gets self return f"{type(self).__name__} {self.order_id} on {self.placed_on}"
@classmethod def from_row(cls, row): # class method: gets cls return cls(row["id"], date.fromisoformat(row["placed_on"]), row["currency"])
@staticmethod def is_supported_currency(code): # static method: gets nothing return code in Order.SUPPORTED_CURRENCIES
class PriorityOrder(Order): pass
row = {"id": "ORD-2", "placed_on": "2026-11-02", "currency": "EUR"}print(Order.from_row(row).describe())print(PriorityOrder.from_row(row).describe()) # cls is PriorityOrderprint(Order.is_supported_currency("JPY"), Order.from_row(row).is_supported_currency("USD"))Output:
OrderV1Order ORD-2 on 2026-11-02PriorityOrder ORD-2 on 2026-11-02False Truefrom_row uses cls(...), so calling it on PriorityOrder builds a PriorityOrder. is_supported_currency needs no state at all, and calling it through the class or an instance gives the same result.
How it works
Section titled “How it works”Three kinds of method
Section titled “Three kinds of method”| Instance method | @classmethod |
@staticmethod |
|
|---|---|---|---|
| First argument | self (the instance) |
cls (the class it was accessed through) |
none |
| Called on the class | Order.describe(order): you pass the instance |
Order.from_row(row) |
Order.is_supported_currency("EUR") |
| Called on an instance | order.describe() |
order.from_row(row): the instance is ignored except for its type |
order.is_supported_currency("EUR") |
| Can read or write instance state | Yes | No | No |
| Sees subclass overrides of class attributes | Through type(self) |
Through cls |
Only by naming a class explicitly |
| Typical use | Behavior of one object | Alternative constructors, class-level configuration, registries | Pure helpers that belong to the class’s API |
What the decorators store
Section titled “What the decorators store”Methods are descriptors. A function object has a __get__ method that returns a bound method when it is accessed through an instance. classmethod and staticmethod are wrapper objects with their own __get__: classmethod.__get__ binds the underlying function to the class, and staticmethod.__get__ returns the function unchanged.
class Order: def describe(self): return "instance"
@classmethod def build(cls): return cls
@staticmethod def validate(code): return code.startswith("ORD-")
# What is stored in the class namespace:for name in ("describe", "build", "validate"): print(f"{name:9} stored as {type(vars(Order)[name]).__name__}")
o = Order()# What attribute access returns (the descriptor's __get__ result):print(type(Order.describe).__name__, type(o.describe).__name__, o.describe.__self__ is o)print(type(Order.build).__name__, Order.build.__self__ is Order, o.build.__self__ is Order)print(type(Order.validate).__name__, Order.validate is o.validate)
# The underlying function is still reachable.print(vars(Order)["build"].__func__.__name__, vars(Order)["validate"].__wrapped__.__name__)
# Since Python 3.10 a staticmethod object is callable, even inside the class body.class Sku: @staticmethod def normalize(code): return code.strip().upper()
DEFAULT = normalize(" sku-0 ")
print(Sku.DEFAULT)Output:
describe stored as functionbuild stored as classmethodvalidate stored as staticmethodfunction method Truemethod True Truefunction Truebuild validateSKU-0Reading the output:
- The class namespace holds a
function, aclassmethodobject and astaticmethodobject. Order.describeis the raw function in Python 3 (there are no “unbound methods”), whileo.describeis a bound method whose__self__iso.Order.buildando.buildare both bound methods with__self__set to the class.Order.validateando.validateare the very same function object.- The wrappers expose the original function as
__func__, and since Python 3.10 also as__wrapped__, together with copied__name__,__doc__and annotations. - Since Python 3.10 a
staticmethodobject is callable directly, so it can be used inside the class body itself.
Pitfalls the descriptor model explains
Section titled “Pitfalls the descriptor model explains”# Chaining classmethod and property was removed in Python 3.13.class Config: @classmethod @property def region(cls): return "eu-west"
print(type(Config.region).__name__) # not "str": the property is never invokedtry: Config.region()except TypeError as exc: print("TypeError:", exc)
# A class-level counter: cls.attr += 1 creates a new attribute on the subclass.class Order: created = 0
@classmethod def create(cls): cls.created += 1 # reads inherited value, writes to cls return cls()
class PriorityOrder(Order): pass
Order.create(); PriorityOrder.create(); PriorityOrder.create()print(Order.created, PriorityOrder.created, "created" in vars(PriorityOrder))
# Python 3.14: functools.partial is a method descriptor, so it binds like a function.from functools import partial
def fee(order, percent): return f"{percent}% fee"
class Checkout: card_fee = partial(fee, percent=2) flat_fee = staticmethod(partial(lambda percent: f"{percent}% flat", percent=1))
c = Checkout()print(c.card_fee(), c.flat_fee())Output:
methodTypeError: 'property' object is not callable1 3 True2% fee 1% flat- Chaining
@classmethodwith@propertyno longer works. Python 3.9 allowed class methods to wrap other descriptors, which made “class properties” possible; that was deprecated in 3.11 and removed in 3.13. In 3.14 the wrapped property is bound as if it were a function, soConfig.regionis a bound method and calling it fails. Use a plain class attribute, a metaclass property, or a@classmethodyou call explicitly. cls.counter += 1writes to the subclass. The read finds the inherited value, but the assignment creates a new attribute on whichever classclsis.Order.createdstays at 1 whilePriorityOrderkeeps its own count. Write to the defining class explicitly (Order.created += 1) if the counter should be shared.functools.partialbinds in Python 3.14. It is now a method descriptor, so a partial stored as a class attribute receives the instance as its first argument, like a function. Wrap it instaticmethod()if it should not.
Realistic example
Section titled “Realistic example”OrdersPortal’s OrderApiClient is built in three ways: from environment variables in production, with fixed settings in tests, and directly in code. Class methods provide the named constructors, and a static method parses the timeout so it can be tested on its own. A subclass with different defaults inherits every constructor unchanged.
from collections.abc import Mappingfrom typing import Self
class OrderApiClient: DEFAULT_TIMEOUT = 5.0
def __init__(self, base_url: str, token: str, *, timeout: float | None = None): self.base_url = base_url.rstrip("/") self.token = token self.timeout = timeout or self.DEFAULT_TIMEOUT
def __repr__(self): return f"{type(self).__name__}({self.base_url!r}, timeout={self.timeout})"
# Alternative constructors: return cls(...) so subclasses get their own type. @classmethod def from_env(cls, env: Mapping[str, str]) -> Self: return cls(env["ORDERS_API_URL"], env["ORDERS_API_TOKEN"], timeout=cls.parse_timeout(env.get("ORDERS_API_TIMEOUT")))
@classmethod def for_tests(cls) -> Self: return cls("https://orders.example.test", "test-token", timeout=0.1)
# Pure helper: no instance or class state needed. @staticmethod def parse_timeout(raw: str | None) -> float | None: if raw is None or not raw.strip(): return None value = float(raw) if value <= 0: raise ValueError(f"timeout must be positive, got {raw!r}") return value
def order_url(self, order_id: str) -> str: return f"{self.base_url}/orders/{order_id}"
class RetryingOrderApiClient(OrderApiClient): DEFAULT_TIMEOUT = 10.0 max_retries = 3
env = {"ORDERS_API_URL": "https://orders.example.test/api/", "ORDERS_API_TOKEN": "dummy"}print(OrderApiClient.from_env(env))print(RetryingOrderApiClient.from_env(env)) # same factory, subclass resultprint(RetryingOrderApiClient.for_tests().order_url("ORD-1001"))print(OrderApiClient.parse_timeout(" 2.5 "))try: OrderApiClient.from_env(env | {"ORDERS_API_TIMEOUT": "0"})except ValueError as exc: print("ValueError:", exc)Output:
OrderApiClient('https://orders.example.test/api', timeout=5.0)RetryingOrderApiClient('https://orders.example.test/api', timeout=10.0)https://orders.example.test/orders/ORD-10012.5ValueError: timeout must be positive, got '0'The return annotation Self (from typing, Python 3.11) tells type checkers that RetryingOrderApiClient.from_env() returns a RetryingOrderApiClient. Inside from_env, cls.parse_timeout(...) rather than OrderApiClient.parse_timeout(...) lets a subclass replace the parser too. The standard library uses the same pattern: dict.fromkeys(), datetime.fromisoformat() and int.from_bytes() are all class methods.
Common mistakes
Section titled “Common mistakes”- Hard-coding the class in a factory. A static method or module function that returns
Order(...)breaks subclassing. Use@classmethodandcls(...). - Using
@staticmethodfor code that reads class attributes.is_supported_currencyabove namesOrder.SUPPORTED_CURRENCIES, so a subclass that changes the set is ignored. If the helper reads class-level configuration, make it a class method. - Making everything a static method. A helper that is not part of the class’s public API, and would be useful elsewhere, is clearer as a module-level function.
- Mutating class state from
cls. Counters and caches written throughclssplit per subclass, as shown above. - Stacking
@classmethodon@property. Removed in Python 3.13; it silently produces a bound method instead of a value. - Forgetting that
__init_subclass__and__class_getitem__are implicit class methods. Writing@classmethodon them is allowed but unnecessary; writing them withselfis misleading.
When to use it and when not to
Section titled “When to use it and when not to”| You need | Use |
|---|---|
| Behavior that reads or changes one object | Instance method |
| A named way to construct the class, which must work for subclasses | @classmethod returning cls(...) |
| Class-level configuration or a registry that subclasses may override | @classmethod |
| A pure function that is part of the class’s API (validation, parsing) | @staticmethod |
| A general utility with no tie to the class | Module-level function |
| A computed attribute on instances | @property |
Compatibility
Section titled “Compatibility”classmethod() and staticmethod() exist in every Python 3 release; the decorator syntax arrived in Python 2.4. Python 3.10 gave both wrappers __wrapped__ and the wrapped function’s metadata, and made static methods callable as plain functions. Python 3.9 let class methods wrap other descriptors; that was deprecated in 3.11 and removed in 3.13. Python 3.14 made functools.partial a method descriptor. typing.Self requires Python 3.11.
Interview questions
Section titled “Interview questions”1. What does PriorityOrder.from_row(row) return if from_row is a @classmethod defined on Order that returns cls(...)?
A PriorityOrder. cls is the class through which the method was accessed, not the class where it was defined.
2. How do classmethod and staticmethod work under the hood?
Both are non-data descriptors stored in the class dictionary. On attribute access, classmethod.__get__ returns a method bound to the class (type(obj) if accessed through an instance); staticmethod.__get__ returns the underlying function unchanged. Plain functions bind to the instance through their own __get__.
3. When is a static method better than a module-level function?
When the function is conceptually part of the class’s API (callers expect Order.is_valid_id(...)), when subclasses might override it and callers reach it through self or cls, or when it keeps a related helper discoverable in the class namespace. Otherwise a module function is simpler and easier to reuse.
4. Senior scenario: OrdersPortal’s Order class has grown twelve from_* class methods for CSV, JSON, three partner formats and test fixtures. Reviews are slow and every change to Order.__init__ breaks several. How would you restructure?
Keep one or two class methods that express the domain (Order.create(...), perhaps Order.from_dict(...)), and move format-specific parsing into separate parser functions or adapter classes that produce the canonical input and call one constructor. Test fixtures belong in test factories, not in production classes. Keep cls(...) in the remaining factories so subclasses still work, type them with Self, and route all construction through a single validated path so __init__ changes are made once.
Key takeaways
Section titled “Key takeaways”- Instance methods get
self, class methods getcls, static methods get nothing. @classmethodwithcls(...)is the right way to write alternative constructors that work for subclasses.- Both decorators are descriptors; the class stores wrapper objects, attribute access binds or unwraps them.
- Writing class state through
clssplits it per subclass;@classmethod @propertywas removed in Python 3.13. - Prefer a module function to a static method when the helper is not part of the class’s API.
Related pages
Section titled “Related pages”- Descriptors: the
__get__protocol behind method binding. - @property: computed attributes on instances.
- super(): calling a parent’s class method from an override.
- Metaclasses:
__init_subclass__, an implicit class method. - dataclasses: generated constructors that pair well with
from_*class methods. - Decorators introduction: how decorator syntax works.
- Object-oriented programming: classes and methods from the beginning.