0%

Your First Classes and Objects · practice

Give an Object Behavior

The Question class now creates every instance with a prompt and an answer. To see how behavior can move beside the state it uses, return briefly to labels. A separate can compare some text with a label:

def matches(label, text):
    return text == label.text

The function needs the text stored on a label, and its result describes that label. A class can keep this behavior beside the state it uses by defining an instance :

class Label:
    def __init__(self, text, color):
        self.text = text
        self.color = color

    def matches(self, text):
        return text == self.text

The method is called through an instance:

label = Label("Review", "blue")
print(label.matches("Review"))

Python supplies the instance as self. The "Review" becomes text.

A responsibility has found a home

The method does not make the program shorter in an important way. It makes the design clearer:

  • a Label knows its own text;

  • a Label decides whether other text matches;

  • other parts of the program do not need to reach into the and repeat that rule.

That is a responsibility: a piece of work one part of the program promises to handle.

In label.matches("Review"), which object becomes self?

Keep the first question method simple. Transfer the label pattern by comparing the response with this question’s answer. Later designs can decide whether to ignore capitalization or surrounding spaces.

Task

Complete is_correct so it returns whether response equals this question’s answer.

After your works, use Step in the exercise editor. Move into the is_correct call and look for self and response in the current method frame.