问题
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