2) Classes, Objects, and Methods Lesson

Why Use a Python Class

4 min to complete · By Martin Breuss

Now that you've read over a high-level theoretical overview of object-oriented programming, you might wonder what the point is in the first place. You've written great programs before, and you never needed to create your own classes. So why would you want to make any classes yourself?

Cooking With Python

In the following lessons, you'll work through a practice example of building an Ingredient class with Python. On the way, you'll cover the most important aspects of object-oriented programming in Python, and you might just end up with a great new soup recipe at the end :)

A bowl of soup - Photo by https://unsplash.com/@ellaolsson Ella Olsson on Unsplash

It's midday, you're hungry, and it's about time for you to cook something. But you're also not quite ready to leave your keyboard and stop learning to program for the day, so you'll prepare yourself for the task by writing some Python code first.

For today's wholesome meal, you want to use a couple of ingredients. You want to store these ingredients in your program so that you can work with them.

Without a Class

Initially, you might want to use a list for that:

ingredients = ["carrot", "pea", "squash"]

And if you only needed to store the names of the ingredients, this would be a great choice. But you also want to keep track of the amounts of each ingredient and potentially many other things.

Another option could be to use a dictionary instead. This allows you to map the name of each ingredient to a list or another dictionary that contains more information about the food item:

ingredients = {
                'carrots': {'name': 'carrot', 'amount': 3},
                'peas': {'name': 'pea', 'amount': 12}
              }

That seems better than the list! But what if you now wanted to use this information to write a recipe:

print(f"Let's take {ingredients['carrots']['amount']} of {ingredients['carrots']['name']} and {ingredients['peas']['amount']} of {ingredients['peas']['name']}.")

Ugh... That's a little unwieldy to work with! Accessing the attributes quickly becomes very wordy and difficult. Looks like a dictionary might not be the best data structure for storing your ingredients and writing a recipe.

You might wish that there was a more intuitive way of doing this. Today's your lucky day because there is! In the next lesson, you'll see how you can model the data for your ingredients in a custom class.

Summary: Why Use a Python Class

  • This lesson starts with planning the Ingredient class
  • A list doesn't offer the ability to store multiple attributes like names and amounts
  • Many attributes can be stored in a dictionary, but accessing attributes is difficult