22.7 Exercises
From Foundations of Python ProgrammingGNU FDL 1.3Original pagePython1 class period1 exerciseNot autograded
22.7 Exercises
Read first in the book: 22.1 Introduction: Class Inheritance, 22.2 Inheriting Variables and Methods, 22.3 Overriding Methods, 22.4 Invoking the Parent Class's Method, 22.5 Multiple inheritance, 22.6 Tamagotchi Revisited.
For exercises, you can expand the Tamagotchi game even further. Try these out.
Here's all the code we just saw for our new and improved game, with a few additions. You can run this and play the game again.
Exercise 1
-
Change the above code to allow you to adopt a Tiger pet (that you're about to create). HINT: look at the
whichtypefunction, and think about what's happening in the code for that function. -
Now, modify the code to define a new class,
Tiger. TheTigerclass should inherit from theCatclass, but its default meow count should be5, not3, and it should have an extra instance method,roar, that prints out the stringROOOOOAR!. -
Next, modify the code so that when the
himethod is called for theTigerclass, theroarmethod is called. HINT: You'll have to call one instance method inside another, and you'll have to redefine a method for theTigerclass. See the overriding methods section. -
Now, modify the code to define another new class,
Retriever. This class should inherit fromLab. It should be exactly likeLab, except instead of printing justI found the tennis ball!when thefetchmethod is called, it should sayI found the tennis ball! I can fetch anything!. -
Add your own new pets and modifications as you like -- remember, to use them in the game, you'll also have to alter the
whichtypefunction so they can be used in game play. Otherwise, you'll have different classes that may work just fine, but you won't see the effects in the game, since the code that actually makes the game play is found in the second half of the provided code (look for thewhileloop!).
Open the
01folder and editmain.py. This one is not graded, so check it yourself.
For teachers
22.7 Exercises
Students read Foundations of Python Programming's “Exercises” in CS Room and work through its 1 Python coding exercise.
- Time: 1 class period
Reading first
- 22.1 Introduction: Class Inheritance
- 22.2 Inheriting Variables and Methods
- 22.3 Overriding Methods
- 22.4 Invoking the Parent Class's Method
- 22.5 Multiple inheritance
- 22.6 Tamagotchi Revisited
Exercises
| Folder | Grading | Tests |
|---|---|---|
01 | Not graded; students check it themselves | 0 |