Unable to call static method inside another static method

Question:

I have a class which has static methods and I want to have another static method within this class to call the method but it returns NameError: name ''method_name' is not defined

Example of what I’m trying to do.

class abc():
    @staticmethod
    def method1():
        print('print from method1')

    @staticmethod
    def method2():
        method1()
        print('print from method2')

abc.method1()
abc.method2()

Output:

print from method1
Traceback (most recent call last):
  File "test.py", line 12, in <module>
    abc.method2()
  File "test.py", line 8, in method2
    method1()
NameError: name 'method1' is not defined

What is the best way to work around this?

I’d like to keep the code in this format where there is a class which contains these static methods and have them able to call each other.

Asked By: Josh Ackland

||

Answers:

It doesn’t work because method1 is a property of abc class, not something defined in a global scope.

You have to access it by directly referring to the class:

    @staticmethod
    def method2():
        abc.method1()
        print('print from method2')

Or using a classmethod instead of staticmethod, which will give methods access to its class object. I recommend using this way.

    @classmethod
    def method2(cls): # cls refers to abc class object
        cls.method1()
        print('print from method2')
Answered By: KokoseiJ

@staticmethod cannot call other static methods while @classmethod can call them. In short, @classmethod is more powerful than @staticmethod.

I explain more about @staticmethod and @classmethod in my answer for @classmethod vs @staticmethod in Python and also explain about instance method in my answer for What is an "instance method" in Python?:

Answered By: Kai – Kazuya Ito