Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading