Applying wraps a function inside a staticmethod descriptor object so Python does not bind self (the instance) or cls (the class) as the implicit first argument when called via either ClassName.method(...) or instance.method(...)—letting you namespace pure utility or validation functions logically inside a class without coupling them to instance or class state.
Basic Example
class Temperature:
def __init__(self, celsius: float) -> None:
self.celsius = celsius
# 1. Static method: receives NO implicit `self` or `cls` argument
@staticmethod
def c_to_f(celsius: float) -> float:
return (celsius * 9 / 5) + 32
def to_fahrenheit(self) -> float:
# Can be called via `self.c_to_f(...)` or `Temperature.c_to_f(...)`
return self.c_to_f(self.celsius)
# Callable directly on the class without instantiating an object:
print(Temperature.c_to_f(25.0)) # Output: 77.0
# Also callable on an instance (`t` is NOT passed as the first argument):
t = Temperature(100.0)
print(t.c_to_f(0.0)) # Output: 32.0
print(t.to_fahrenheit()) # Output: 212.0
Key Details & Edge Cases
- How
works under the hood (Descriptor Protocol):- Regular functions in Python implement
__get__(self, instance, owner)so accessingobj.fnreturns a bound method that prependsobjasself. wraps the function in a non-data descriptor whose__get__simply returns the unmodified underlying function regardless of whether it is accessed on the class (Temperature.c_to_f) or on an instance (t.c_to_f).- Since Python 3.10,
staticmethodobjects are also directly callable (wrappers can be invoked as functions inside the class body during class creation, e.g., to initialize class constants).
- Regular functions in Python implement
- Subclasses and inheritance with
:- Subclasses inherit
methods normally (class SmartTemp(Temperature): pass; SmartTemp.c_to_f(20)works) and can override them—but because areceives neitherselfnorcls, it cannot dynamically inspect or construct the subclass (cls(...)). Whenever a helper needs to instantiate the class or read subclass-overridden attributes, useinstead.
- Subclasses inherit
- When to choose
vs. a module-level function:- In Python, module-level functions are first
You must log in or register to comment.
