Weeks 13: More Classes and Objects

Why objects?

Objects provide encapsulation. In computer science, encapsulation can mean one of two related things:

  • A mechanism for restricting access to some of the object’s components.

  • A mechanism for bundling of data with methods operating on that data.

Classes and objects provide both mechanisms. On larger programming projects, it is common to have different people work on different parts of the program. Classes are a good place to divide the work. In this case, the class writer and the class user can agree on an interface. The interface specifies what methods the class has and what they should do. The class user doesn’t need to know or care how a class is implemented, only how to use the objects. The class writer doesn’t need to know or care how a class is used, only how to implement the interface.

Object-oriented programming also facilitates modularity. Modular programming is a software design technique that focuses on separating the functionality of a program into independent, interchangable pieces (aka "modules"), so that each piece contains everything needed to perform one aspect of the desired functionality.

Class definitions provide reusability, i.e., they let you create/reuse functionality while hiding technical details. With classes, you can rapidly create new and complex code by grabbing existing code "off the shelf" and reusing it for novel purposes.

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.