You are on page 1of 1

104

Chapter 8. Classes and Object-Oriented Programming


Figure 8.5 contains a class that can be used to keep track of the grades of a
collection of students. Instances of class Grades are implemented using a list
and a dictionary. The list keeps track of the students in the class. The
dictionary maps a students identification number to a list of grades.
Notice that getGrades returns a copy of the list of grades associated with a
student, and getStudents returns a copy of the list of students. The
computational cost of copying the lists could have been avoided by simply
returning the instance variables themselves. Doing so, however, is likely to lead
to problems. Consider the code
allStudents = course1.getStudents()
allStudents.extend(course2.getStudents())

If getStudents returned self.students, the second line of code would have the
(probably unexpected) side effect of changing the set of students in course1.
The instance variable isSorted is used to keep track of whether or not the list of
students has been sorted since the last time a student was added to it. This
allows the implementation of getStudents to avoid sorting an already sorted list.
Figure 8.6 contains a function that uses class Grades to produce a grade report
for some students taking 6.00, the MIT course for which this book was
developed.

You might also like