Class Notes Week 13


Topics

Monday Wednesday Friday


Classes/Objects Recap

Last week we started discussing classes, and you gained some experience writing your own classes.

pizza.serveSlice()

Bad Habit: Direct Data Access in Python

This section describes a feature of Python that you should not use in CS21, but may accidentally use. We encourage you to use good class design. Further discussion of this topic is covered in CS35.

In Python, by default, you can also directly access an object's data using dot notation:

pizza = Pizza("pepperoni")
pizza.topping = "blueberries"

In this sense, data in Python is "public". It's also possible to add data members to an object post-creation.

pizza.cheese = "mozzarella"

This is bad programming style. It is dangerous to allow users to modify data however they want. For example, you might want to have a BankAccount class which contains an attribute balance and methods deposit(dollars), withdraw(dollars), and printBalance(). Using getter and setter methods to view/manipulate data instead of accessing data directly can prevent bad behavior from users. For example:

>>> myAccount = BankAccount(1000)
>>> myAccount.printBalance()
$1000
>>> myAccount.withdraw(10000)
I am sorry, but your balance is not high enough.
>>> myAccount.balance = 10000000000

Do not access data directly. One nice thing about defining classes: you get to decide how users access an object's data.


Why Objects?

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

Classes and objects provide both mechanisms.

On larger programming projects, it's 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 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/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.

Class definitions 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 using it for novel purposes.

Exercise:

In fish.py, we've partially implemented a Fish class representing a fish using 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.