Python call static method in class | Example code

To call a static method in class use a static method from within the body of the class, and define the static method using the built-in staticmethod function as a decorator in Python.

Python call a static method in class example

Simple example code staticmethod objects apparently have a func attribute storing the original raw function.

class Klass(object):

    @staticmethod  # use as decorator
    def stat_func():
        print("Static method")
        return 42

    _ANS = stat_func.__func__()  # call the staticmethod

    def method(self):
        ret = Klass.stat_func()
        return ret

Output:

Python call static method in class

How to call static methods inside the same class in Python

Answer: you can use the @classmethod decorator. The static method can be called without creating an object or instance.

class A:
    @staticmethod
    def methodA():
        print('method A')

    @classmethod
    def methodB(cls):
        cls.methodA()


A.methodA()
A.methodB()

Output:

method A
method A

Source: stackoverflow.com

Do comment if you have any doubts and suggestions about this Python method tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.