The staticmethod()
is a decorator function that is used to create static methods for a given class.
Static methods do not receive the class or instance as the first argument. They are not associated with any specific instance or class data. As a result, they are commonly used to define utility functions that are not dependent on instance or class-specific data.
Static methods can be accessed both through class instances and directly through the class itself.
Syntax:
@staticmethod
def my_static_method():
#body
or
def my_static_method():
#body
Myclass.some_method = staticmethod(my_static_method)
When you define a function inside a class, it is, by default, treated as an instance method meaning that you can only access it from class instances. If you call the method with the class itself, it will be treated as a regular function. The @staticmethod
and the @classmethod
decorators are used to override this behaviour.
The following examples demonstrates the difference between instance and static methods.
Calling example_method()
with an instance raises an error because the class assumes by default that the method is an instance method and consequently tries to pass the instance e
to the method which does not define any parameters.
By using the @staticmethod
decorator, the method becomes accessible to instances without accepting the instance as the first argument.
Compare the static methods with the class methods, which are defined with the @classmethod decorator.