python className未定义NameError [英] python className not defined NameError
问题描述
我有一个需要实例化的类才能调用它包含的方法.当我从另一个类访问它时,它工作正常,但是当我从终端运行时,它说:
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
粘贴代码:
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)
推荐答案
问题是您的if __name__ == "__main__"
块位于类定义中.这将导致错误,因为if
中的代码将在将类绑定到名称之前作为创建的类的一部分运行.
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
),则它应该可以正常工作:
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)
这篇关于python className未定义NameError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!