- 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 4: A Person Constructor
What happens when you want to create 100 people? In the Step 2 code you’d have to manually create every dict and put the talk() function in it, which is ridiculous. We have computers for repetitive boring work, so let’s use what we know so far to create a new constructor() for our people.
We’ll use everything you know so far to create a function that “constructs” people:
Listing 44.4: ex44_4.py
1 def Person_new(name, age, eyes): 2 person = { 3 "name": name, 4 "age": age, 5 "eyes": eyes, 6 } 7 8 def talk(words): 9 print(f"I am {person['name']} and {words}") 10 11 person['talk'] = talk 12 13 return person 14 15 becky = Person_new("Becky", 39, "green") 16 17 becky['talk']("I am talking here!")
This code is using the following concepts:
Person_new() is a constructor, which means it creates a new person dict and attaches the talk() function to it.
The talk() function is a closure, which means it has access to the person that is created at the top of the Person_new() function.
It adds this talk() function to the person just like you did in Step 2, but since this is a closure from Step 3, we don’t have to manually give it the person
It returns this new person with its closure-based talk(), and then we can use it just like before, but it’s a bit cleaner.
If we compare the Step 2 final line with this line, we have the following:
1 # from step 2, see the two becky uses? 2 becky['talk'](becky, "I am talking here!") 3 4 # from step 4, now only one becky 5 becky['talk']("I am talking here!")
With the Person_new() constructor, we can remove this extra becky variable, which makes it far more reliable to use. This also means we could potentially give different kinds of people different talk() functions if we wanted.