[英]python returns nameError for class name not being defined
I am trying to code a program that calls on an established class from another python file called student.我正在尝试编写一个程序,该程序从另一个名为 student 的 python 文件中调用一个已建立的类。 In the file student, a class called StudentInfo is established and init checks if the data is valid (eg. grade must be between 9-12, course code must fit format, etc.) I am trying to first take the user's inputs here.
在文件 student 中,建立了一个名为 StudentInfo 的类, init检查数据是否有效(例如,成绩必须在 9-12 之间,课程代码必须符合格式等)我试图首先在此处获取用户的输入。
import student
import transcript
def add_student(data):
dataDict = data
ID = str(len(dataDict) + 1)
student = StudentInfo(ID, input("Enter the student\'s last name: "), input("Enter the student\'s first name: "), input("Enter the student\'s grade: "), transcript.add_transcript(), input("Is the student registered: "))
return dataDict
When I try to define student as an object of class StudentInfo, it returns NameError: name 'StudentInfo' is not defined.
当我尝试将学生定义为 StudentInfo 类的对象时,它返回
NameError: name 'StudentInfo' is not defined.
I'm not sure what I'm doing wrong.我不确定我做错了什么。 I thought it might be the inputs but when I removed them it seemed to do the same thing.
我认为这可能是输入,但是当我删除它们时,它似乎做了同样的事情。 Please help and thanks in advance.
请帮助并提前致谢。
You need student.StudentInfo
if you're using import student
.如果您使用
import student
则需要student.StudentInfo
。
Alternatively, you can import as:或者,您可以导入为:
from student import StudentInfo
To use the code that you have now.使用您现在拥有的代码。
It appears you forgot to prefix StudentInfo
with student
.看来您忘了在
StudentInfo
加上student
。 You can either replace:您可以替换:
import student
With:和:
from student import StudentInfo
Or you can replace:或者你可以替换:
student = StudentInfo(ID, input("Enter the student\'s last name: "), input("Enter the student\'s first name: "), input("Enter the student\'s grade: "), transcript.add_transcript(), input("Is the student registered: "))
With:和:
student = student.StudentInfo(ID, input("Enter the student\'s last name: "), input("Enter the student\'s first name: "), input("Enter the student\'s grade: "), transcript.add_transcript(), input("Is the student registered: "))
On a side note: You shouldn't name variables after imports.附带说明:您不应该在导入后命名变量。 Rename the variable
student
to something else.将变量
student
重命名为其他名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.