Python staticmethod decorator: @staticmethod

The static method decorator, or @staticmethod, is used to define methods inside a class as static methods. For example:

class fresherearth:
    @staticmethod
    def statfun(x):
        print("Value of x:", x)

fresherearth.statfun("Hey!")

Here is its output:

Value of x: Hey!

Note: Static methods do not have access to what the class is. The static method is just a function, without having access to the object of the class (where the static method is defined) or its internals. The differentiation between these two is provided in class methods versus static methods.

Note: Also, there is no "self" or "cls" parameter for the static method. When we need to define a normal static method inside a class that can be called directly using the class, we need the @staticmethod decorator to do the task.

Python @staticmethod decorator syntax

The syntax of the @staticmethod decorator in Python is given below.

@staticmethod
def myfun(arg1, arg2, arg3, ..., argN):
    # definition code goes here

Python @staticmethod decorator example

Here is a simple example of the @staticmethod decorator in Python. This program employs the @staticmethod syntax to define static methods within the "fresherearth" class:

class fresherearth:
    @staticmethod
    def myfun(a, b, c, s):
        print("The value of a:", a)
        print("The value of b:", b)
        print("The value of c:", c)
        print("The value of s:", s)


fresherearth.myfun(100, 200, 300, "Python is Fun!")

The sample output produced by this Python program is shown in the snapshot given below:

python staticmethod decorator

Advantages of the @staticmethod decorator in Python

Disadvantages of the @staticmethod decorator in Python

Python Online Test


« Previous Tutorial Next Tutorial »