编译时出现此错误:
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
。
答案 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