Home »
Python
Static methods in Python
Python static methods: In this tutorial, we are going to learn about the static methods with examples in Python programming language.
Submitted by Sapna Deraje Radhakrishna, on December 11, 2019
Python static methods
Static methods are similar to python class-level methods while the static method is bound to a class rather than the object for the given class.
Creating a python static method
1) Using staticmethod()
Below example demonstrates the implementation of staticmethod(),
class Multiply:
def perform(x,y):
return x * y
Multiply.perform = staticmethod(Multiply.perform)
print("Multiplication of {} and {} is {}".format(5,4, Multiply.perform(4, 5)))
Output
Multiplication of 5 and 4 is 20
2) Using @staticmethod
Below example demonstrates the implementation of @staticmethod,
class Multiply:
@staticmethod
def perform(x,y):
return x * y
print("Multiplication of {} and {} is {}".format(5,4,Multiply.perform(4, 5)))
Output
Multiplication of 5 and 4 is 20
Note: The @staticmethod is more pythonic way to declare a method to be a static method.
Advantages of using Static method
- Very clear use case
- When there is a use case not wrt object but wrt class, the method is made a static method. This approach is advantageous while implementing utilities method.
- In a static method, the self is not passed as a first argument.
ADVERTISEMENT
ADVERTISEMENT