Home > Articles

From Dictionaries to Objects

This chapter is from the book

You should review the following exercises before doing this one:

  • Exercise 24, Introductory Dictionaries, to refresh your understanding of Dictionaries

  • Exercise 25, Dictionaries and Functions, for how you can put functions in dictionaries and call them

  • Exercise 26, Dictionaries and Modules, for how modules are just dictionaries behind the scenes and how changing the underlying __dict__ changes the module

In this exercise you’ll learn about Object-Oriented Programming by creating your own little object system using the previous information.

Step 1: Passing a Dict to a Function

Imagine you want to record information about people and then have them say things. Maybe this is a little video game with little people growing food in a small town. You want to know their name, age, and hair color. You also need a way to make them talk. Using what you know, you may invent this code:

Listing 44.1: ex44_1.py

 1   becky = {
 2       "name": "Becky",
 3       "age": 34,
 4       "eyes": "green"
 5   }
 6
 7   def talk(who, words):
 8       print(f"I am {who['name']} and {words}")
 9
10   talk(becky, "I am talking here!")

Let’s break this down to confirm you understand the code:

  1. I create a becky variable that has all the information about Becky

  2. I then have a function named talk that accepts this becky variable and prints out a little dialogue from that character

  3. Then I call this function, passing in the becky variable and something for Becky to say

What’s interesting is you can use this function on anything that has the same “signature” as the becky variable. If you created 1,000 characters with this same dict, the talk() function would still work.

What You Should See

When you run the code for Step 1, you should see this output:

1   I am Becky and I am talking here!

This doesn’t change in the later versions of this code.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.