Search code examples
pythonprogram-entry-point

Class name not found in main method - python


So my code is:

class myClass:

    @staticmethod
    def func():
        print('foo')

    if __name__ == "__main__":
        myClass.func()

But when I run it I get the following error:

Traceback (most recent call last):
  File "myClass.py", line 1, in <module>
    class myClass:
  File "myClass.py", line 8, in myClass
    myClass.func()
NameError: name 'myClass' is not defined

How do I fix this?


Solution

  • This is an indentation issue.

    class myClass:
    
        @staticmethod
        def func():
            print('foo')
    
    if __name__ == "__main__":
        myClass.func()
    

    The above will work fine in a Python interpreter. Currently, in your code, it is trying to run myClass.func() inside the if block INSIDE the class definition, i.e. when it is trying to create myClass, it is trying to run myClass.func() and it is failing with the error mentioned in your post.