hw29: Class inheritance with food
- Due before the beginning of class on Wednesday, April 10
This homework will reinforce concepts from our current unit on classes, specifically focusing these concepts:
- inheritance
- subclasses and superclasses
- class variables
- instance variables
Your task
Create a file called food.py
which contains two classes that you
write, Food
and Yogurt
, where Yogurt
is a subclass of Food
.
The Food
class should be initialized with a food’s name, meal name,
and calorie count. The Food
class has two functions: info()
displays
the food information in a certain format shown below, and eat()
adds
that food’s calories to a running total and prints out the current count
as shown below.
(Hint: you will need a class variable in the Food
class to store the
total number of calories eaten so far.)
The Yogurt
class is a subclass of Food
. It it initialized only with
the flavor; every yogurt is for lunch and has 150 calories. The Yogurt
class will have one function (in addition to those inherited from
Food
): calling stir()
prints a message specifying which flavor of
yogurt is being stirred.
(Note, the Yogurt class should not have to define the info()
or
eat()
functions; those should just be defined once in the Food
class.)
Here is a file I will use to test your code:
from food import Food, Yogurt
bagel = Food('bagel', 'breakfast', 350)
pizza = Food('pizza', 'dinner', 800)
lemyo = Yogurt('lemon')
plainyo = Yogurt('plain')
bagel.info() # prints "bagel is a breakfast food with 350 calories"
pizza.info() # prints "pizza is a dinner food with 800 calories"
lemyo.info() # prints "lemon yogurt is a lunch food with 150 calories"
plainyo.info() # prints "plain yogurt is a lunch food with 150 calories"
bagel.eat() # prints "350 calories so far"
lemyo.stir() # prints "Stirring your lemon yogurt"
lemyo.eat() # prints "500 calories so far"
pizza.eat() # prints "1300 calories so far"
plainyo.stir() # prints "Stirring your plain yogurt"
plainyo.eat() # prints "1450 calories so far"
Running this file should produce the following output:
bagel is a breakfast food with 350 calories
pizza is a dinner food with 800 calories
lemon yogurt is a lunch food with 150 calories
plain yogurt is a lunch food with 150 calories
350 calories so far
Stirring your lemon yogurt
500 calories so far
1300 calories so far
Stirring your plain yogurt
1450 calories so far
(Note: if you write any testing code inside your food.py
file, make
sure you put it under a if __name__ == '__main__'
check, so that your
testing code does not run when I import food
from another file.)
Submit command
To submit files for this homework, run one of these commands:
submit -c=sd212 -p=hw29 food.py
club -csd212 -phw29 food.py