[英]NameError: name 'Class' is not defined
当我编译时,我收到此错误:
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
。
Python 源文件由解释器从上到下解释。
因此,当您在类Main
调用Reading()
,它还不存在。 您需要交换声明以将Reading
放在Main
之前。
您需要在Main
之前定义Reading
您需要在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())
前向声明在 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.