python错误NameError:name' ofclass'没有定义

时间:2017-05-25 12:17:29

标签: python python-2.7 python-3.x

我有一项任务要弄清楚下面的代码是做什么的。它看起来像是在python2中构建但我想使用python3。我已经安装了它需要的argparse并设置了必要的文件路径,但每次我在命令行中运行程序时都会遇到这些问题。

Traceback (most recent call last):
  File "C:\Users\Name\pythonScripts\Noddy.py", line 6, in <module>
    class Noddy:
  File "C:\Users\Name\pythonScripts\Noddy.py", line 63, in Noddy
    if __name__ == '__main__': main()
  File "C:\Users\Name\pythonScripts\Noddy.py", line 57, in main
    ent = Noddy.make(fools)
NameError: name 'Noddy' is not defined

代码如下。

#! python3


class Noddy:
    def __init__(self, x):
        self.ant = None
        self.dec = None
        self.holder = x

    @classmethod
    def make(self, l):
        ent = Noddy(l.pop(0))
        for x in l:
            ent.scrobble(x)
        return ent

    def scrobble(self, x):
        if self.holder > x:
            if self.ant is None:
                self.ant = Noddy(x)
            else:
                self.ant.scrobble(x)
        else:
            if self.dec is None:
                self.dec = Noddy(x)
            else:
                self.dec.scrobble(x)

    def bubble(self):
        if self.ant:
            for x in self.ant.bubble():
                yield x
            yield self.holder
            if self.dec:
                for x in self.dec.bubble():
                    yield x

    def bobble(self):
        yield self.holder
        if self.ant:
            for x in self.ant.bobble():
                yield x
        if self.dec:
            for x in self.dec.bobble():
                yield x

    def main():
        import argparse
        ap = argparse.ArgumentParser()
        ap.add_argument("foo")
        args = ap.parse_args()

        foo = open(args.foo)
        fools = [int(bar) for bar in foo]
        ent = Noddy.make(fools)

        print(list(ent.bubble()))
        print
        print(list(ent.bobble()))

    if __name__ == '__main__': main()

1 个答案:

答案 0 :(得分:0)

您的def main()if __name__=='__main__'已经在课程中编写。解释器在定义类时尝试执行它们,但不能,因为类Noddy在类定义完成之前不存在。

修复缩进,以便main内容之外

class Noddy:
    def __init__(self, x):
        self.ant = None
        self.dec = None
        self.holder = x
    # other methods INSIDE the class
    # ...

# Notice the indentation — this function is OUTSIDE the class
def main():
    # whatever main is supposed to do
    # ...

if __name__=='__main__':
    main()