【问题标题】:NameError: name 'Class' is not definedNameError:名称“类”未定义
【发布时间】:2019-03-27 10:49:16
【问题描述】:

编译时出现此错误:

Traceback (most recent call last):
  File "c:/Users/dvdpd/Desktop/ProjectStage/Main.py", line 1, in <module>
    class Main:
  File "c:/Users/dvdpd/Desktop/ProjectStage/Main.py", line 6, in Main
    test = Reading()
NameError: name 'Reading' is not defined

代码:

class Main:
    print("Welcome.\n\n")
    test = Reading()
    print(test.openFile)


class Reading:
    def __init__(self):
        pass

    def openFile(self):
        f = open('c:/Users/dvdpd/Desktop/Example.txt')
        print(f.readline())
        f.close()

我不能使用 Reading 类,我不知道为什么。 MainReading 在同一个文件中,所以我认为我不需要 import

【问题讨论】:

  • 编辑:谢谢大家,抱歉这个愚蠢的问题!
  • 您也可以将问题标记为已删除。

标签: python python-3.x nameerror


【解决方案1】:

前向声明在 Python 中不起作用。因此,只有按如下方式创建 Main 类的对象才会报错:

class Main:
    def __init__(self):
        print("Welcome.\n\n")
        test = Reading()
        print(test.openFile)

# Main() # This will NOT work

class Reading:
    def __init__(self):
        pass

    def openFile(self):
        f = open('c:/Users/dvdpd/Desktop/Example.txt')
        print(f.readline())
        f.close()

# Main() # This WILL work

【讨论】:

    【解决方案2】:

    Python 源文件由解释器从上到下进行解释。

    所以,当你在类Main 中调用Reading() 时,它还不存在。您需要交换声明以将 Reading 放在 Main 之前。

    【讨论】:

      【解决方案3】:

      你需要在Main之前定义Reading

      【讨论】:

        【解决方案4】:

        您需要在class Main 之前定义class Reading

        class Reading:
            def __init__(self):
                pass
        
            def openFile(self):
                f = open('c:/Users/dvdpd/Desktop/Example.txt')
                print(f.readline())
                f.close()
        
        
        class Main:
            print("Welcome.\n\n")
            test = Reading()
            print(test.openFile())
        

        【讨论】:

          猜你喜欢
          • 2020-01-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-01-24
          • 1970-01-01
          • 2017-09-14
          相关资源
          最近更新 更多