Python

Python Call Static Method Within Class

In Python, we have different types of functions/methods, such as built-in functions, user-defined functions, and many more. Basically, it is a block of code that is only executed when it is invoked. Users can pass data into it, known as arguments/parameters. Functions can be static which is part of the class and used for making the class’s utility methods. To call the static methods, the class reference can be used.

The outcomes from this blog are:

What is a “static” Method in Python?

In Python, static methods can be invoked without an object for that particular class and cannot update the position of an object.

Advantages of the Static Methods in Python

The advantages of the static methods are listed below:

    • Static methods have clear use cases.
    • Users can make static methods when they need functionality not with respect to the object but the entire class.
    • In static methods, users don’t require to pass “self” as the first parameter.

How to Invoke “static” Method inside Class in Python?

To invoke a static method within a class in Python, use a static method from within the body of the defined class and define it by utilizing Python’s built-in “@staticmethod” as a decorator.

Example

At first, we constructed a class. Then, utilize the “@staticmethod” decorator to define a static method. After that, call the class method by using the “ClassnName.method_name” and an object of the class. In our case, our class name is “Linuxhint”, the method name is “stat_func()” and the “lxht” is the class object:

class Linuxhint(object):

    @staticmethod # use as decorator
    def stat_func():
    print("This is a Static Method")    


Linuxhint.stat_func()

lxht = Linuxhint()
lxht.stat_func()

 
In the below-provided output, we can see the generated result:


That’s it! We have provided a way to call the static method within the class in Python.

Conclusion

In Python, static methods can be invoked without an object. The “@staticmethod” decorator can be used for defining a static method. This article illustrated the procedure for calling a static method within a class in Python.

About the author

Maria Naz

I hold a master's degree in computer science. I am passionate about my work, exploring new technologies, learning programming languages, and I love to share my knowledge with the world.