Skip to content

Python call static method in class | Example code

  • by

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 calls 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 or suggestions about this Python method tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Your email address will not be published. Required fields are marked *