Namespace for stateless utilities
A class groups a conversion, validation, parsing, or formatting operation that uses only its explicit arguments.
Python · Decorator
@staticmethod turns a class-defined function into a static method that receives no implicit instance or class argument. It can be called through either the class or an instance.
Applying @staticmethod stores the function as a static method, so Python does not supply an instance or class as an implicit first argument. It can be accessed through the class or an instance, and the descriptor can also be called directly while the class body is being defined.
@staticmethod
def f(arg1, arg2, argN): ...class Temperature:
@staticmethod
def celsius_to_fahrenheit(celsius):
return celsius * 9 / 5 + 32
print(Temperature.celsius_to_fahrenheit(20))
print(Temperature().celsius_to_fahrenheit(20))The method performs a conversion without receiving an instance or class argument, and both class and instance access produce the same result.
A class groups a conversion, validation, parsing, or formatting operation that uses only its explicit arguments.
A class body needs to retain a function reference without Python binding it as an instance method.
@staticmethod transforms a method into a static method. Unlike an instance method, it receives no implicit first argument, so it is appropriate when the operation does not need an instance or class.
Follow-up: How can the same behavior be declared without decorator syntax? Define a regular function and assign it in the class as method = staticmethod(regular_function).
A static method can be called through the class, such as C.f(), or through an instance, such as C().f(). Both calls use the arguments supplied by the caller without an automatically added receiver.
Follow-up: Can the descriptor be called during class definition? Yes; the static method descriptor is callable, so a class body can invoke the name after it has been bound.
The decorator is useful when a function belongs conceptually to a class but does not need instance or class state. It also avoids the automatic transformation into an instance method when a function reference is kept in a class body.
Follow-up: What explicit form preserves a regular function reference in a class? Use method = staticmethod(regular_function) inside the class.
classmethodFunction definitionsThe standard type hierarchy