Search code examples
pythonmethodsstatic-methods

Unable to call static method inside another static method


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.


Solution

  • 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')