Fancypants753
Fancypants753

Reputation: 449

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?

Upvotes: 0

Views: 651

Answers (2)

kdheepak
kdheepak

Reputation: 1366

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.

Upvotes: 2

Jishnunand P K
Jishnunand P K

Reputation: 290

class myClass:

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

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

Upvotes: 1

Related Questions