Table of Contents
ToggleIn Python, a static method is a type of method that does not require any instance to be called. It is very similar to the class method but the difference is that the static method doesn’t have a mandatory argument like reference to the object − self or reference to the class − cls.
Static methods are used to access static fields of a given class. They cannot modify the state of a class since they are bound to the class, not instance.
There are two ways to create Python static methods −
Python’s standard library function named staticmethod() is used to create a static method. It accepts a method as an argument and converts it into a static method.
staticmethod(method)
In the Employee class below, the showcount() method is converted into a static method. This static method can now be called by its object or reference of class itself.
class Employee:
empCount = 0
def __init__(self, name, age):
self.__name = name
self.__age = age
Employee.empCount += 1
# creating staticmethod
def showcount():
print (Employee.empCount)
return
counter = staticmethod(showcount)
e1 = Employee("Bhavana", 24)
e2 = Employee("Rajesh", 26)
e3 = Employee("John", 27)
e1.counter()
Employee.counter()
Output:
Executing the above code will print the following result −
3
3
The second way to create a static method is by using the Python @staticmethod decorator. When we use this decorator with a method it indicates to the Interpreter that the specified method is static.
@staticmethod def method_name(): # your code
In the following example, we are creating a static method using the @staticmethod decorator.
class Student:
stdCount = 0
def __init__(self, name, age):
self.__name = name
self.__age = age
Student.stdCount += 1
# creating staticmethod
@staticmethod
def showcount():
print (Student.stdCount)
e1 = Student("Bhavana", 24)
e2 = Student("Rajesh", 26)
e3 = Student("John", 27)
print("Number of Students:")
Student.showcount()
Output:
Running the above code will print the following result −
Number of Students:
3
There are several advantages of using static method, which includes −
Key Takeaway: Master Python static methods—create with @staticmethod, use as utilities, and leverage their predictability in class design!
