Tutorial Study Image

Python staticmethod()

The staticmethod() is used to create a static function. The static method is not bound to the objects, it bound to the class. This means the state of an object cannot be modified by the static methods if it is not bound to it.

syntax of using staticmethod().


staticmethod (function) #Where function indicates function name
 

 

For defining a static method in the class we can use a built-in decorator @staticmethod.We don’t pass an instance of the class when the function is decorated with @staticmethod.Which means we can write a function inside a class but we can’t use the instance of that class.

 

syntax of using @staticmethod decorator.


@staticmethod
def func(args, ...) #Where args indicates function parameters

staticmethod() Parameters:

Takes only one parameter. The parameter is usually a function that needs to be converted as static. We can also use utility functions as parameters.

Parameter Description Required / Optional
Function The name of the function that created as a static method Required

staticmethod() Return Value

It returns the given function as a static method

Input Return Value
Function  Static method of the given function

Examples of staticmethod()in Python

Example 1:Using staticmethod() create a static method



class Mathematics:

    def Numbersadd(x, y):
        return x + y

# create Numbersadd static method
Mathematics.Numbersadd= staticmethod(Mathematics.Numbersadd)

print('The sum is:', Mathematics.Numbersadd(20, 30))
 

Output:

The sum is: 50

Example 2: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 DatesWithSlashes(Dates):
    def getDate(self):
        return Dates.toDashDate(self.date)

date = Dates("20-04-2021")
dateFromDB = DatesWithSlashes("20/04/2021")

if(date.getDate() == dateFromDB.getDate()):
    print("Equal")
else:
    print("Unequal")
 

Output:

Equal

Example 3:How to create static method of a Utility function?


class Dates:
    def __init__(self, date):
        self.date = date
        
    def getDate(self):
        return self.date

    @staticmethod
    def toDashDate(date):
        return date.replace("/", "-")

date = Dates("12-03-2020")
dateFromDB = "12/03/2020"
dateWithDash = Dates.toDashDate(dateFromDB)

if(date.getDate() == dateWithDash):
    print("Equal")
else:
    print("Unequal")
 

Output:

Equal