Home > Software design >  Python - two classes appending user input to the same list, how to display its data within a loop
Python - two classes appending user input to the same list, how to display its data within a loop

Time:12-04

I am new to python programming. I am currently working on a simple program involving Classes. I have one class called Students and another called Instructor, they both accepts input from user and save/append to the same list called college_records.. when it comes to displaying the results I have two methods 'display_student_info()' and 'display_student_info()' within a for loop, I get the error:

                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'

please advise..

CodePudding user response:

The problem is that you have a loop on a list where there are objects from two different classes, but you call the same method "display_student_information()". The thing is, when you loop on an instructor, the instance from its class does not have a such method.

You might want to create a superclass, with a common method "display info", like this :

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)

Then you can loop in a list with Instructors and Students Objects, and display info like this :

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