python className not defined NameError

强颜欢笑 提交于 2019-12-17 21:36:44

问题


I have a class which i need to instantiate in order to call a method that it contains. When I access it from another class it works fine but when i run from terminal it says :

File "myClass.py", line 5, in <module>
  class MyClass:
File "myClass.py", line 23, in ToDict
  td=MyClass()
NameError: name 'MyClass' is not defined

Pasting the code:

class MyClass:
    def convert(self, fl):
        xpD = {}
        # process some stuff
        return xpD

    if __name__ == "__main__":
        source = sys.argv[1]
        td = MyClass()
        needed_stuff = td.convert(source)
        print(needed_stuff)

回答1:


The problem is that your if __name__ == "__main__" block is inside of your class definition. This will cause an error, as the code within the if will be run as part of the class being created, before the class been bound to a name.

Here's a simpler example of this error:

class Foo(object):
    foo = Foo() # raises NameError because the name Foo isn't bound yet

If you format your code like this (that is, with the if unindented at the top level), it should work correctly:

class MyClass:
    def convert(self, fl):
        xpD = {}
        # process some stuff
        return xpD

if __name__ == "__main__":
    source = sys.argv[1]
    td = MyClass()
    needed_stuff = td.convert(source)
    print(needed_stuff)


来源:https://stackoverflow.com/questions/22294192/python-classname-not-defined-nameerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!