0%

Your First Classes and Objects · practice

Let a Quiz Collaborate with Questions

The previous lesson placed several independent Question in one . We can now give that collection to another object that represents the quiz as a whole.

Each Question knows its prompt, its answer, and how to check one response. A Quiz has a different job: it keeps the collection and selects which question should handle a response.

class Quiz:
    def __init__(self, questions):
        self.questions = questions

The Quiz object therefore contains a list whose values are Question objects:

quiz -> Quiz
        questions -> list
                     -> Question
                     -> Question

This arrangement is called composition: one object is built from other objects that keep their own focused jobs.

Delegate the detailed work

The containing object can select one member and ask it to do the detailed work. Reuse the label example from earlier lessons:

class LabelSet:
    def __init__(self, labels):
        self.labels = labels

    def matches(self, index, text):
        label = self.labels[index]
        return label.matches(text)

LabelSet does not duplicate the text-matching rule. It delegates that work to the selected Label. The exercise applies the same collaboration to Quiz and Question.

This division gives each class a focused promise:

  • Question.is_correct(response) checks one question.

  • Quiz.check_answer(index, response) selects a question and delegates.

A Quiz contains Question objects and delegates answer checking to a selected Question.

Put the collaboration in order:

Drag the options into order, or use the arrow buttons.

  • Quiz calls Question.is_correct(response).

  • Question compares the response with its answer.

  • The Boolean result returns to the caller.

  • Quiz selects a Question from its list.

Small assertions let us check the public promise:

assert quiz.check_answer(0, "4")
assert not quiz.check_answer(0, "5")

The assertions do not care what private helper names the classes use. They check what the objects promise to do.

Task

Complete Quiz.check_answer.

Select the question at index, then delegate answer checking to that ’s is_correct . Run the program and keep both assertions passing.