NameError:名称“类”未定义

时间:2019-03-27 10:49:17

标签: python python-3.x nameerror

编译时出现此错误:

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

4 个答案:

答案 0 :(得分:1)

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

因此,当您在类Reading()中调用Main时,该名称尚不存在。您需要交换声明,将Reading放在Main之前。

答案 1 :(得分:1)

您需要在Reading之前定义Main

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

转发声明在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