Your First Classes and Objects · capstone
Capstone project: Project: Replace Quiz Dictionaries with Objects
This chapter began with question Question class, created initialized instances, moved answer checking into a Quiz work with a collection of questions.
The project now combines that sequence into one working quiz model. You will build:
a
Questionclass that creates dependable question; an
is_correctmethod that owns the answer-matching rule;a
Quizclass that contains questions;a
check_answermethod that delegates to one question;a
scoremethod that checks a sequence of responses.
What the classes must support
Other code should be able to create questions, build a quiz, check one answer, and calculate a score:
questions = [
Question("Two plus two?", "4"),
Question("Three plus three?", "6"),
]
quiz = Quiz(questions)
assert quiz.check_answer(0, "4")
assert quiz.score(["4", "5"]) == 1
You may add helpful
Build in small steps
Finish
Question.__init__.Finish
Question.is_correct.Finish
Quiz.__init__.Finish
Quiz.check_answer.Finish
Quiz.score.Run the program and submit it.
Quiz.score receives one response for each question. It should return the number of correct responses.
One clear approach is to start a counter at zero, check_answer returns True.
Review the design
After the project passes, compare it with the dictionary version:
What shape can no longer be created accidentally through the normal constructor?
Which object owns answer checking?
What became easier to read?
What extra structure did the classes introduce?
Classes are valuable when their clearer promises justify that structure. This project gives you a concrete design to evaluate rather than a rule that classes are always better.
Which responsibility belongs most naturally to Question?
Task
Complete the two classes so the final program prints:
Score: 2/3
Submit when your Question Quiz delegates answer checking, and score works for both the provided data and other questions.