HomepageTeaching PageResearch PageResources Page

Homework: Creating Methods

Read sections 17.1, 17.2, 17.3, and 17.4 in the book and try out the code samples. You don't have to do any of the exercises.

Methods are functions that are specific to a single class. You've already seen how to call methods many times. Now we'll create some of our own. Consider again the Recipe class. Instead of directly adding a new element to the list for ingredients, we could create a add_ingredient method like this:

class Recipe(object):
    """Models a recipe to make food.
    attributes: name, ingredients, steps."""
    
    def add_ingredient(self, ingredient):
        """Adds an ingredient to this recipe."""
        self.ingredients.append(ingredient)
        

Okay, there's a bunch of things to mention/clarify/highlight here:

We can create an object and invoke this method by doing the following:

>>> fake_chx_parm = Recipe()
>>> fake_chx_parm.name = "Microwave Chicken Parm"
>>> fake_chx_parm.ingredients = []
>>> fake_chx_parm.steps = []
>>> Recipe.add_ingredient(fake_chx_parm, "5 frozen chicken nuggets")
>>> Recipe.add_ingredient(fake_chx_parm, "1/3 cup pasta sauce")
>>> Recipe.add_ingredient(fake_chx_parm, "1 provolone slice")
>>> fake_chx_parm.ingredients
['5 frozen chicken nuggets', '1/3 cup pasta sauce', '1 provolone slice']
>>>
        

"Wait!" you say. "That's not how we've been invoking methods this semester!" You're completely right. We've been invoking methods on lists and turtles, but in a completely different way. We can still do that, by moving that first element (the subject) out of the parameter list and putting it in front, replacing the class name:

>>> fake_chx_parm = Recipe()
>>> fake_chx_parm.name = "Microwave Chicken Parm"
>>> fake_chx_parm.ingredients = []
>>> fake_chx_parm.steps = []
>>> fake_chx_parm.add_ingredient("5 frozen chicken nuggets")
>>> fake_chx_parm.add_ingredient("1/3 cup pasta sauce")
>>> fake_chx_parm.add_ingredient("1 provolone slice")
>>> fake_chx_parm.ingredients
['5 frozen chicken nuggets', '1/3 cup pasta sauce', '1 provolone slice']
>>>
        

When Python sees a method written in this nice way, it translates it to the other way, using the class of the subject. Then it executes the method. Important: you still need to include self as the first parameter in the method definition. (This is not necessary as in some other languages, such as Java.) Let's finish this up by including a fruitful method to get the number of ingredients.

class Recipe(object):
    """Models a recipe to make food.
    attributes: name, ingredients, steps."""
    
    def add_ingredient(self, ingredient):
        """Adds an ingredient to this recipe."""
        self.ingredients.append(ingredient)
    
    def get_num_ingredients(self):
        """Returns the number of ingredients in this recipe."""
        return len(self.ingredients)
        

Practice invoking this method:

>>> fake_chx_parm = Recipe()
>>> fake_chx_parm.name = "Microwave Chicken Parm"
>>> fake_chx_parm.ingredients = []
>>> fake_chx_parm.steps = []
>>> fake_chx_parm.add_ingredient("5 frozen chicken nuggets")
>>> fake_chx_parm.add_ingredient("1/3 cup pasta sauce")
>>> fake_chx_parm.add_ingredient("1 provolone slice")
>>> fake_chx_parm.get_num_ingredients()
3
>>>