Read sections 17.6 and 17.7 in the book and try out the code samples.
There is another special method that you've been indirectly been using in many classes: __str__. The purpose of this method is to return a string version of the subject. It is automatically called anytime you use str to turn something into a string. Let's add it to our Recipe class:
class Recipe(object):
"""Models a recipe to make food."""
def __init__(self, name):
self.name = name
self.ingredients = []
self.steps = []
def __str__(self):
"""Returns a string version of self."""
string = "Recipe: " + str(self.name) #start the string to build the output
string += "\n\n" #add a line break and a blank line
string += "Ingredients:\n"
for ingredient in self.ingredients:
string += " * " + str(ingredient) + "\n"
string += "\n" #another blank line
string += "Steps:\n"
for i in range(len(self.steps)):
step = self.steps[i]
string += " " + str(i) + ": " + str(step) + "\n"
return string
Now we can use this by calling the str function (different from the __str__ method) on a Recipe:
>>> cup = Recipe("PB Cup")
>>> cup.add_ingredient("Peanut Butter Cup")
>>> cup.add_step("Unwrap it and eat.")
>>> str(cup)
'Recipe: PB Cup
Ingredients:
* Peanut Butter Cup
Steps:
0: Unwrap it and eat.
'
>>>
Now that we have the __str__ method, we don't need our clunky print_recipe function. Why not? Because the str function is automatically applied to each argument in a print statement:
>>> cup = Recipe("PB Cup")
>>> cup.add_ingredient("Peanut Butter Cup")
>>> cup.add_step("Unwrap it and eat.")
>>> print(cup)
Recipe: PB Cup
Ingredients:
* Peanut Butter Cup
Steps:
0: Unwrap it and eat.
>>>
Whenever you create a new class in Python, you should always immediately write two methods: