logical level rather than a syntax-focused level.
You’re thinking not about
Python, but about how to represent the real world in code. When you reach
this point, you’ll realize there are often no right or wrong approaches to
modeling real-world situations. Some approaches are more efficient than
others, but it takes practice to find the most efficient representations. If
your code is working as you want it to, you’re doing well! Don’t be discour-
aged if you find you’re ripping apart your classes and rewriting them several
times using different approaches. In the quest to write accurate, efficient
code, everyone goes through this process.
TRY IT YOURSELF
9-6. Ice Cream Stand: An ice cream stand is a specific kind of restaurant. Write
a class called IceCreamStand that inherits from the Restaurant class you wrote in
Exercise 9-1 (page 162) or Exercise 9-4 (page 166). Either version of the class
will work; just pick the one you like better. Add an attribute called flavors that
stores a list of ice cream flavors. Write a method that displays these flavors.
Create an instance of IceCreamStand, and call this method.
9-7. Admin: An administrator is a special kind of user. Write a class called
Admin that inherits from the User class you wrote in Exercise 9-3 (page 162)
or Exercise 9-5 (page 167). Add an attribute, privileges, that stores a list of
strings like "can add post", "can delete post", "can ban user", and so on.
Write a method called show_privileges() that lists the administrator’s set of
privileges. Create an instance of Admin, and call your method.
9-8. Privileges: Write a separate Privileges class. The class should have one
attribute, privileges, that stores a list of strings as described in Exercise 9-7.
Move the show_privileges() method to this class. Make a Privileges instance
as an attribute in the Admin class. Create a new instance of Admin and use your
method to show its privileges.
9-9. Battery Upgrade: Use the final version of electric_car.py from this section.
Add a method to the Battery class called upgrade_battery(). This method
should check the battery size and set the capacity to 65 if it isn’t already. Make
an electric car with a default battery size, call get_range() once, and then
call get_range() a second time after upgrading the battery. You should see an
increase in the car’s range.
Importing Classes
As you add more functionality to your classes, your files can get long, even
when you use inheritance and composition properly. In keeping with the
overall philosophy of Python, you’ll want to keep your files as uncluttered as
possible. To help, Python lets you store classes in modules and then import
the classes you need into your main program.
Classes 173