When working on object-oriented problems, we may find it difficult to invoke a method repeatedly through the class object. Python assists us in this process by allowing us to create static methods with the Python staticmethod() function. This built-in function converts a method into a static method. The static method is bound to a class rather than the class’s objects. This indicates that a static method for a class can be invoked without the need for an object for that class.
Definition
- The Python staticmethod() built-in function is used to return a static method for a given function.
Python staticmethod()
The static methods allow you to isolate the utility methods into different sub-modules. For better understanding and convenience of use, we can construct static methods in different classes. The syntax for Python’s staticmethod() function is as below.
-
Syntax
There are 2 ways in which we can define the Python staticmethod() method.
staticmethod(function_name)
The @staticmethod decorator is available in subsequently newer versions of Python
class C(object):
   @staticmethod
   def func(args, ...)
Note – To call a static method, we use the following syntax:
class_name.static_method_name()
-
Python staticmethod() Parameters
The staticmethod() function accepts a single parameter:
function_name = name of the defined function which needs to be converted to a static method
-
Return value from staticmethod()
Returns a static method for a function passed as a parameter to the Python staticmethod().
What is a Static Method?
- A static method is one that is bound to the class rather than the class’s object.
- An implicit initial parameter is not passed to a static method.
- Because they are members of the class, static methods cannot access or modify the object’s state.
- They do not necessitate the construction of a class instance. As a result, they are not affected by the state of the object.
- The static method is similar to a function in a Python script, but it is located within the class body.
- It cannot have cls or self parameters, unlike the class method.
Example 1: Create a static method using staticmethod()
When you wish to construct a static method declared in the class, use staticmethod(). It should be noted that the procedure should not include the self argument.
Example 1
# Python program to illustrate staticmethod()
class Math:
   def addition(a, b):
       print('Addition of 2 numbers is:', a+b)
# Create static method for addition() function
Math.addition = staticmethod(Math.addition)
Math.addition(7, 3)
Output
Addition of 2 numbers is: 10
Example 2
# Python program to illustrate staticmethod()
class Display:
   def Student(FN, LN):
       print('Full name:', FN, LN)
# Create static method for Student() function
Display.Student = staticmethod(Display.Student)
Display.Student('James', 'Cullen')
Output
Full name: James Cullen
Example 2: Create a static method using @staticmethod
Another method to define the static method is to use the @staticmethod decorator. This is also a recommended method for defining a static method.
Example
# Python program to illustrate @staticmethod decorator
class Result:
   @staticmethod
   def multiply(x, y, z):
       print('Multiplication:', x*y*z)
Result.multiply(2, 3, 4)
Output
Multiplication: 24
When do you use static methods?
-
Grouping utility function to a class
Utility functions are one of the applications for using static methods. These are ways for doing common, frequently re-used actions that are useful for completing normal programming tasks. As a result, if we have a utility function that does not need to access any class attributes and only needs the parameters, we can declare it as a static method.
Example
# Create a utility function as a static method
class Dates:
   def __init__(self, date):
       self.date = dateÂ
   def getDate(self):
       return self.date
   @staticmethod
   def toDashDate(date):
       return date.replace('/', '-')
date = Dates('1-8-2021')
newdate = '1/8/2021'
Dashdate = Dates.toDashDate(newdate)
if(date.getDate() == Dashdate):
   print('Both Dates are Equal')
else:
   print('Both Dates are Unequal')
Output
Both Dates are Equal
We implemented a utility method toDashDate within Dates to convert slash-dates to dash-dates. It is a static method because it does not need to access any Dates properties and only needs the parameters.
-
Having a single implementation
When we don’t want subclasses of a class to change or override a specific implementation of a method, we use static methods. In this scenario, we declare a static method to prevent inherited classes from affecting our method.
Example
# How inheritance works with static method
class Dates:
   def __init__(self, date):
       self.date = date   Â
   def getDate(self):
       return self.date
   @staticmethod
   def toDashDate(date):
       return date.replace('/', '-')
class SlashDates(Dates):
   def getDate(self):
       return Dates.toDashDate(self.date)
date = Dates('1-8-2021')
newdate = SlashDates('1/8/2021')
if(date.getDate() == newdate.getDate()):
   print('Dates are Equal')
else:
   print('Dates are Unequal')
Output
Dates are Equal
We don’t want the SlashDates subclass to override the static utility function toDashDate because it only has one use, which is to turn dates to dash-dates.
Frequently Asked Questions
Q1. What is a static method in Python?
The static method is a method that is bound to the class rather than the class’s object. An implicit initial parameter is not required to be passed to a static method. Because they are members of the class, static methods cannot access or modify the object’s state. They do not necessitate the construction of a class instance. As a result, they are not affected by the state of the object. The static method is similar to a function in a Python script, but it is located within the class body. It cannot have cls or self parameters, unlike the class method.
Q2. What is the difference between a static method and the class method in Python?
class method | static method |
The first parameter of a class method is cls. | The static method does not accept any specific parameter. |
A class method has the ability to access or modify the class state. | A class state cannot be accessed or modified by a static method. |
We use the @classmethod decorator to create a class method. | Here we use the @staticmethod decorator to create a static method. |
It can be used to define a factory method that returns class instances. | It is unable to return a class object. |
Q3. What is a static method with example?
The Python staticmethod() built-in function is used to return a static method for a given function. The static methods allow you to isolate the utility methods into different sub-modules. For better understanding and convenience of use, we can construct static methods in different classes.
There are 2 ways to implement the static method.
-
Create a static method using staticmethod()
Example
class Power:
   def Result(x, y):
       z = x ** y
       print(x, 'raised to', y, 'is:', z)
Power.Result = staticmethod(Power.Result)
Power.Result(2, 3)
Output
2 raised to 3 is: 8
-
Create a static method using @staticmethod decorator
Example
from math import *
class Pizza:
   @staticmethod
   def Area(radius):
       area = pi * (radius ** 2)
       print('Area of Pizza is:', round(area, 4))
Pizza.Area(5)
Output
Area of Pizza is: 78.5398
Leave a Reply