Chapter 4
Your First Classes and Objects
From Question Dictionaries to Question Objects
The Chapter 3 project processed complete attempt
Question dictionaries follow the same rule. A familiar quiz question looks like this:
question = {
"prompt": "What does len('cat') return?",
"answer": "3",
}
This design works. Dictionaries are not a mistake, and a class is not automatically better. In this chapter, we will examine what happens when a growing program depends on every question dictionary having exactly the same shape.
Compare these questions:
questions = [
{
"prompt": "What does len('cat') return?",
"answer": "3",
},
{
"text": "Which keyword starts a function?",
"answer": "def",
},
]
The second dictionary uses text where the program expects prompt. Python can create that dictionary without complaint. The problem appears later, when another part of the program tries to use the missing key.
The behavior lives somewhere else
A function can check an answer:
def is_correct(question, response):
return response == question["answer"]
The question data lives in one place, while the rule for working with that data lives in another. As the program grows, a change to the dictionary may also require changes in every function that uses its keys.
That is the design pressure we will address. We want a dependable kind of
always represents one quiz question;
carries the information a question needs;
provides the operations that belong to a question.
The next lesson introduces Python’s way to define such a value. First, check that the problem is clear.
Why does the second dictionary cause trouble for code that reads question["prompt"]?
Try the failure
The editor contains two question dictionaries and a function that displays their prompts. Run it, read the final line of the error, and then repair the inconsistent key.
Repair only the inconsistent key for now. First make the existing design work again. A useful abstraction should solve a problem you understand, not hide one you have not examined.
Task
Run the program and read the final line of the
Change the inconsistent key so both prompts print. Then answer this question for yourself: what had to stay coordinated for the program to work?