Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
731 views
in Technique[技术] by (71.8m points)

class - 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

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...