HomepageTeaching PageResearch PageResources Page

Homework: Functions on Objects

Read sections 16.1, 16.2, 16.3, and 16.4 in the book and try out the code samples. You don't have to do any of the exercises.

When you have a function that takes an object parameter, you can access all the attributes of that object. We saw this last time in print_recipe:

def print_recipe(recipe):
    """Nicely prints a Recipe object."""
    print("Recipe:", recipe.name)
    print() #Add a blank line
    print("Ingredients:")
    for ingredient in recipe.ingredients:
        print("  *", ingredient)
    print() #another blank line
    print("Steps:")
    for i in range(len(recipe.steps)):
        step = recipe.steps[i]
        print(" " + str(i) + ":", step)
        

Let's create some other functions that take Recipe objects.

def num_steps(recipe):
    """Returns the number of steps in a recipe."""
    return len(recipe.steps)
        

We can have functions that return a Recipe also:

def has_more_ingredients(recipe_0, recipe_1):
    """Returns the recipe with more ingredients."""
    if len(recipe_0.ingredients) < len(recipe_1.ingredients):
        return recipe_1
    else:
        return recipe_0
        

Try these out with the recipes we created last time:

>>> fake_chx_parm = Recipe()
>>> fake_chx_parm.name = "Microwave Chicken Parm"
>>> fake_chx_parm.ingredients = []
>>> fake_chx_parm.steps = []
>>> fake_chx_parm.ingredients.append("5 frozen chicken nuggets")
>>> fake_chx_parm.ingredients.append("1/3 cup pasta sauce")
>>> fake_chx_parm.ingredients.append("1 provolone slice")
>>> fake_chx_parm.steps.append("Microwave the frozen chicken nuggets in a small bowl for 1 minute, 25 seconds.")
>>> fake_chx_parm.steps.append("Pour the pasta sauce over one side of the heated nuggets.")
>>> fake_chx_parm.steps.append("Place the provolone slice over the pasta sauce.")
>>> fake_chx_parm.steps.append("Put everything back in the microwave for 25 more seconds, then enjoy!")
>>>
>>> cup = Recipe()
>>> cup.name = "PB Cup"
>>> cup.ingredients = ["Peanut Butter Cup"]
>>> cup.steps = ["Unwrap it and eat."]
>>> recipe = has_more_ingredients(fake_chx_parm, cup)
>>> recipe.name
'Microwave Chicken Parm'
>>> num_steps(cup)
1
>>>