简体   繁体   English

在主要方法中找不到类名-python

[英]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? 我该如何解决?

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. 上面的代码在Python解释器中可以正常工作。 Currently, in your code, it is trying to run myClass.func() inside the if block INSIDE the class definition, ie 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. 当前,在您的代码中,它正在尝试在class定义内部的if块中运行myClass.func() ,即,当它尝试创建myClass ,它正在尝试运行myClass.func() ,并且失败了。您的帖子中提到的错误。

class myClass:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM