Python Helpful Tutorials Tutorial
Python Static Method
In this tutorial we will see What is Python static method and how to create it and use it. We will also see what advantages it offers and what are the disadvantage of using static method in Python.
What is Static Method in Python
Static methods in python are similar in concept as in other languages like C#. Static methods are bound to the class, not with the object of the class. It means user can call the static method without creating the object of the class, which indicates that static method can not modify the state of the object directly, because its not part of the object.
Creating Python Static Method
There are manily two ways to create static method in Python. Let's see each of them:
Using @staticmethod
This is the annotation style declaration of static method.
class Calculation:
@staticmethod
def multiply_numbers(a, b):
return a * b
print('Result is:', Calculation.multiply_numbers(10, 35))
Using staticmethod()
In this approach, we create static method in below way, notice how it is difference than annotation style declaration.
class Calculation:
def multiply_numbers(a, b):
return a * b
# Creating a static method
Calculation.multiply_numbers = staticmethod(Calculation.multiply_numbers)
print('Result is:', Calculation.multiply_numbers(10, 35))
Advantages of Static Methods
Static methods are very useful to create utility function which can be used widely in the application.