2017-05-25 106 views
-3

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

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() 
+0

您是否包含了整个错误?我只是看到一个堆栈跟踪? – OptimusCrime

+0

使用@classmethod和self会导致错误。改用cls。 –

+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()