[英]NameError: name 'Class' is not defined
When I compile I get this error:当我编译时,我收到此错误:
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
Code:代码:
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()
I can't use the class Reading
and I don't know why.我不能使用类
Reading
,我不知道为什么。 Main
and Reading
are in the same file so I think I don't need an import
. Main
和Reading
在同一个文件中,所以我认为我不需要import
。
Python source files are interpreted top to bottom by the interpreter. Python 源文件由解释器从上到下解释。
So, when you call Reading()
inside class Main
, it does not exist yet.因此,当您在类
Main
调用Reading()
,它还不存在。 You need to swap the declarations to put Reading
before Main
.您需要交换声明以将
Reading
放在Main
之前。
您需要在Main
之前定义Reading
You need to define class Reading
before class Main
.您需要在
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())
Forward declaration doesn't work in Python.前向声明在 Python 中不起作用。 So you'll get an error only if you create an object of the Main class as follows:
因此,仅当您按如下方式创建 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.