- Step 1: Passing a Dict to a Function
- Step 2: talk inside the Dict
- Step 3: Closures
- Step 4: A Person Constructor
- Study Drills
Step 2: talk inside the Dict
The first problem with this design is any part of your code that wants to make these characters talk has to know about the talk() function. That’s not too large a problem, but maybe you want each character to have special talk() functions that do something different.
One way to fix this is to “attach” the talk() function to the dict itself like this:
Listing 44.2: ex44_2.py
1 def talk(who, words): 2 print(f"I am {who['name']} and {words}") 3 4 becky = { 5 "name": "Becky", 6 "age": 34, 7 "eyes": "green", 8 "talk": talk # see this? 9 } 10 11 becky['talk'](becky, "I am talking here!")
The differences between this version and the first one are:
I move the talk() function to the top so we can reference it later.
I then put the function in the becky dictionary with "talk": talk. Remember, a function is just like any other variable, which means you can pass it to other functions and place it in a list or dict
Then the last line calls the talk() function in one move.
That last line might cause you problems, so let’s break just that line down:
becky['talk']: Python gets the contents of the becky dictionary assigned the 'talk' key. It’s exactly like if you did print(becky['age']) to get the age key of becky. Don’t get confused by the characters after this.
(becky, "I am talking here!"): You know that Python sees () after a variable as a function call, and you just got the contents of becky['talk'], so this calls those contents as a function. It then passes the variable becky to it and the string "I am talking here!"
You can take the next step to study this code by breaking it apart into two lines of code like this:
1 becky_talk = becky['talk'] 2 becky_talk(becky, "I am talking here!")
What confuses people is they see all those characters in the original “one-liner” and their brain treats it like one big word. The way you analyze these is to break them apart into separate lines using variables.