Skip to content
Related Articles

Related Articles

Python staticmethod() Function

Improve Article
Save Article
Like Article
  • Last Updated : 02 Dec, 2021

Python staticmethod() function is used to convert a function to a static function. A static method is a method that belongs to a class rather than an instance of a class. The static methods do not require instantiation. 

Syntax: staticmethod(function)

Parameter:

The staticmethod() method takes a single argument i.e. it takes a function as an argument.

Returns:

The staticmethod() returns a static method of the function passed as the argument.

Example 1: Implementation for application of staticmethod()

Python3




class demoClass:
 
    def greet(msg):
        return msg
 
 
# convert the add to a static method
demoClass.greet = staticmethod(demoClass.greet)
 
# we can access the method without
# creating the instance of class
print(demoClass.greet("hai"))


Output:

hai

In the above code a class with method greet() is created, then it was converted to the static method using staticmethod(), and it is called without creating an instance, as we have discussed earlier it is not required to create an instance of the class to call a static method.

Example 2: Implementation for application of staticmethod()

Python3




class demoClass:
 
    def __init__(self, a, b):
        self.a = a
        self.b = b
 
    def add(a, b):
        return a+b
 
    def diff(self):
        return self.a-self.b
 
 
# convert the add to a static method
demoClass.add = staticmethod(demoClass.add)
 
# we can access the method without creating
# the instance of class
print(demoClass.add(1, 2))
 
# if we want to use properties of a class
# then we need to create a object
Object = demoClass(1, 2)
print(Object.diff())


Output:

3
-1

If we don’t require to use the class properties then we can use static methods, here in the above code add() method does not use any class properties so it is made static using staticmethod() and the diff method needs to be called by creating an instance because it uses class properties.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!