Example Class: A Gradebook: - Create Class That Includes Instances of Other Classes Within It - Concept
Example Class: A Gradebook: - Create Class That Includes Instances of Other Classes Within It - Concept
Example: A Gradebook
class Grades(object): """A mapping from students to a list of grades""" def __init__(self): """Create empty grade book""" self.students = [] # list of Student objects self.grades = {} # maps idNum -> list of grades self.isSorted = True # true if self.students is sorted def addStudent(self, student): """Assumes: student is of type Student Add student to the grade book""" if student in self.students: raise ValueError('Duplicate student') self.students.append(student) self.grades[student.getIdNum()] = [] self.isSorted = False
Example: A Gradebook
class Grades(object): def addGrade(self, student, grade): """Assumes: grade is a float Add grade to the list of grades for student""" try: self.grades[student.getIdNum()].append(grade) except KeyError: raise ValueError('Student not in grade book') def getGrades(self, student): """Return a list of grades for student""" try: # return copy of student's grades return self.grades[student.getIdNum()][:] except KeyError: raise ValueError('Student not in grade book)
Example: A Gradebook
class Grades(object):
def allStudents(self): """Return a list of the students in the grade book""" if not self.isSorted: self.students.sort() self.isSorted = True return self.students[:] #return copy of list of students
Setting up an example
ug1 = UG('Jane Doe', 2014) ug2 = UG('John Doe', 2015) ug3 = UG('David Henry', 2003) g1 = Grad('John Henry') g2 = Grad('George Steinbrenner') six00 = Grades() six00.addStudent(g1) six00.addStudent(ug2) six00.addStudent(ug1) six00.addStudent(g2) for s in six00.allStudents(): six00.addGrade(s, 75) six00.addGrade(g1, 100) six00.addGrade(g2, 25) six00.addStudent(ug3)
This prints out the list of student names sorted by idNum Why not just do
for s in six00.students: print s
This violates the data hiding aspect of an object, and exposes internal representation
If I were to change how I want to represent a grade book, I should only need to change the methods within that object, not external procedures that use it