Python-两个类将用户输入附加到同一列表中,如何在循环中显示其数据



我是python编程的新手。我目前正在做一个涉及类的简单程序。我有一个叫Students的类和另一个叫Coacher的类,它们都接受用户的输入,并保存/附加到同一个名为college_records的列表中。。当谈到显示结果时,我在for循环中有两个方法"display_student_info(("one_answers"display_student_info((",我得到了错误:

for item in college_records:
item.display_student_information()
for item in college_records:
item.display_instr_information()
'...
AttributeError: 'Instructor' object has no attribute 'display_student_information'

请告知。。

问题是,在列表上有一个循环,其中有来自两个不同类的对象,但您调用了相同的方法"display_student_information(("。问题是,当你在一个讲师上循环时,它类中的实例没有这样的方法。

您可能想要创建一个超类,使用一个通用方法";显示信息";,像这样:

class CollegePerson:
def __init__(self, name):
self.name = name
def display_info(self):
print(self.name)

class Instructor(CollegePerson):
def __init__(self, name, field):
super(Instructor, self).__init__(name=name)
self.field = field
def display_info(self):
super(Instructor, self).display_info()
print(self.field)

class Student(CollegePerson):
def __init__(self, name, year):
super(Student, self).__init__(name=name)
self.year = year
def display_info(self):
super(Student, self).display_info()
print(self.year)

然后你可以在一个包含讲师和学生对象的列表中循环,并显示如下信息:

for college_person in my_list:
print(college_person.display_info())

最新更新