我定义了一个名为 Teacher 的类,并在名为 Person 的类中调用它。当 Person 运行并且满足条件时,会引发 NameError,表示我尚未定义 Teacher。我不知道未定义的 OfficeStaff 类是否会影响这一点。这是我的 Person 类:
class Person:
role = input("Hello, my name is PySchool. I am not really AI, but I am close enough. My job is to simulate activities at a school, no matter your role. So, what is your role?")
def writePaperwork(job):
if job == "Student":
Student.doHomework()
elif job == "Teacher":
Teacher.writeTest()
elif job == "Student Life Mentor":
print("Student Life Mentors don't have to write paperwork!")
elif job == "Office Staff":
OfficeStaff.writePlanForSchoolYear()
else:
print("That is not a valid job.")
def comeToGHC(hoursWorkStart, hoursWorkEnd):
hoursOffStart = hoursWorkEnd + 1
hoursOffEnd = "8:30"
if hoursOffEnd == hoursOffStart:
print("I'm sorry, you can't come to GHC after work. Try adjusting your schedule.")
else:
print(f"You can come to GHC at {hoursOffStart} to {hoursOffEnd}.")
try:
hoursForWorkStart = int(input("When does your time for work start? Input the hour number."))
hoursForWorkEnd = int(input("When does your time for work end? Input the hour number."))
except(ValueError):
print("Please enter an integer. There cannot be a decimal point.")
writePaperwork(role)
comeToGHC(hoursForWorkStart, hoursForWorkEnd)
稍后我会定义教师和学生。这可能看起来像是一所陌生的学校,因为它是一所在线学校。我的名字错误是这样的:
Traceback (most recent call last):
File "/home/MGKitty/Unit6/Activity1.py", line 36, in <module>
class Person:
File "/home/MGKitty/Unit6/Activity1.py", line 61, in Person
writePaperwork(role)
File "/home/MGKitty/Unit6/Activity1.py", line 42, in writePaperwork
Teacher.writeTest()
NameError: name 'Teacher' is not defined
我尝试将 Student 和 Teacher 类移到 Person 类之前,但是因为它们继承了 Person 类,所以程序引发了另一个 NameError ,指出 Person 未定义。
您可以创建一个通用的def,例如学校;然后你可以分离每个部分及其功能。一般来说:
def school(entry):
if entry == "Teacher":
# Teacher functions go here
elif entry == "Student":
# Student functions go here
elif entry == "Office Staff":
# Office Staff functions go here
然后,在课堂上:
if job == "Student":
school("Student")
elif job == "Teacher":
school("Teacher")
# The rest goes here, as you like and wish to do
您也必须对这些提供的代码进行更改,我只是想更轻松更好地分享我的想法。