Week 14: More Classes, and Dictionaries
Week 14 Goals
-
Implement more complex classes (e.g., with lists as instance variables)
-
Finish Examples from the previous week
-
Learn about the dictionary type (
dictin python)
Week 14 Files
-
student-gpa.py: An extension of theStudentclass from the previous week, where we add a list containing the GPA values of each semester. -
fish.py: Creating a virtual aquarium by defining aFishclass -
wordcount.py: An introduction to dictionaries by counting the frequencies of words in Pride and Prejudice.
Exercise: Extend the Student Class
Extend the Student class from the previous week to track the student’s GPA for each semester. To do this, you should do the following:
-
Add a
gpasinstance variable which is a list of floats -
Add an int instance variable
num_semesters -
Add a method
semester_gpathat takes as a parameter a new GPA value (a float) and (1) adds that GPA to thegpaslist and (2) incrementsnum_semesters. -
Add a method
average_gpamethod that computes the average gpa over all semesters. -
Modify the
__str__method to include this new information about gpas
Exercise: Aquarium
In fish.py, we’ve partially implemented a Fish class representing a fish, using the Zelle graphics library. Complete the Fish class by adding, at a minimum, an eye and a pupil to the Fish class. Test the Fish class by creating ten fish with random locations, sizes, and colors. Then, write a moveFish(dx) method, which moves the fish to the right by dx pixels.
Add a method offScreen(self) to your Fish class to test whether the fish is completely out of the window to the right, and if so it moves it back to just off the left side of the window.
| do not worry about detecting the exact instant the fish is off the screen; a rough overestimate will suffice. |
Use this method to make the ten fish swim around and around the aquarium.