NameError:未定义名称“Class”

当我编译时,我收到此错误:


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,我不知道为什么。 Main并且Reading在同一个文件中,所以我认为我不需要import.


幕布斯7119047
浏览 189回答 3
3回答

当年话下

您需要定义Reading之前Main

呼唤远方

Python 源文件由解释器从上到下解释。所以,当你Reading()在 class 内部调用时Main,它还不存在。您需要交换声明放在Readingbefore&nbsp;Main。

繁花不似锦

前向声明在 Python 中不起作用。因此,仅当您按如下方式创建 Main 类的对象时,您才会收到错误:class Main:&nbsp; &nbsp; def __init__(self):&nbsp; &nbsp; &nbsp; &nbsp; print("Welcome.\n\n")&nbsp; &nbsp; &nbsp; &nbsp; test = Reading()&nbsp; &nbsp; &nbsp; &nbsp; print(test.openFile)# Main() # This will NOT workclass Reading:&nbsp; &nbsp; def __init__(self):&nbsp; &nbsp; &nbsp; &nbsp; pass&nbsp; &nbsp; def openFile(self):&nbsp; &nbsp; &nbsp; &nbsp; f = open('c:/Users/dvdpd/Desktop/Example.txt')&nbsp; &nbsp; &nbsp; &nbsp; print(f.readline())&nbsp; &nbsp; &nbsp; &nbsp; f.close()# Main() # This WILL work
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python