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 (dict in python)

Week 14 Files

  • student-gpa.py: An extension of the Student class from the previous week, where we add a list containing the GPA values of each semester.

  • fish.py: Creating a virtual aquarium by defining a Fish class

  • 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 gpas instance variable which is a list of floats

  • Add an int instance variable num_semesters

  • Add a method semester_gpa that takes as a parameter a new GPA value (a float) and (1) adds that GPA to the gpas list and (2) increments num_semesters.

  • Add a method average_gpa method 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.