Python Static Methods: How to Create and Use Them
Learn how to define and use static methods in Python. Static methods do not require an instance of the class to be called and are similar to class methods but without the self
or cls
parameters. Discover the syntax and examples for creating static methods in your Python classes.
Python - Static Methods
A static method in Python does not require an instance to be called. It is similar to a class method but does not have the mandatory argument like self (reference to the object) or cls (reference to the class).
Creating Static Methods
Static methods can be created using:
staticmethod()
Function@staticmethod
Decorator
Using staticmethod()
Function
The staticmethod()
function converts a method into a static method.
Syntax
staticmethod(method)
Example
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("Aditi", 24)
e2 = Employee("Vikram", 26)
e3 = Employee("Sara", 27)
e1.counter()
Employee.counter()
Output
3
3
Using @staticmethod
Decorator
The @staticmethod
decorator is another way to create static methods.
Syntax
@staticmethod
def method_name():
# your code
Example
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("Aditi", 24)
e2 = Student("Vikram", 26)
e3 = Student("Sara", 27)
print("Number of Students:")
Student.showcount()
Output
Number of Students:
3
Advantages of Static Methods
Static methods offer several advantages:
- Can be used as utility functions to perform frequently re-used tasks.
- Invoked using the class name, eliminating dependency on instances.
- Predictable behavior, unchanged regardless of class state.
- Prevent method overriding by declaring a method as static.