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.
class Example:
def __init__(self):
self.name = 'instance'
def example_method():
print('Hello, world')
e = Example()
e.example_method()
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.
class Example:
def __init__(self):
self.name = 'instance'
@staticmethod
def example_method():
print('Hello, World!')
e = Example()
e.example_method()
class Calculator:
def __init__(self):
self.name = 'calculator instance'
@staticmethod
def add(num1, num2):
return '{} + {} = {}'.format(num1, num2, num1 + num2)
@staticmethod
def subtract(num1, num2):
return '{} - {} = {}'.format(num1, num2, num1 - num2)
@staticmethod
def multiply(num1, num2):
return '{} x {} = {}'.format(num1, num2, num1 * num2)
@staticmethod
def divide(num1, num2):
return '{} / {} = {}'.format(num1, num2, num1 / num2)
print(Calculator.add(1, 2)) #calling static methods from the class itself
print(Calculator.multiply(10, 20))
c = Calculator()
print(c.divide(200, 50))#calling static method from instance.
print(c.multiply(30, 40))
print(c.add(40, 60))
print(c.subtract(10, 20))
Compare the static methods with the class methods, which are defined with the @classmethod decorator.