0%

Your First Classes and Objects · practice

Create Valid Question Instances

The first Question class gave us a new kind of , but it did not yet guarantee that a question was complete. We created an empty instance and attached its attributes afterward:

question = Question()
question.prompt = "What does len('cat') return?"
question.answer = "3"

Because those steps were separate, it was easy to stop too soon and leave out the answer:

question = Question()
question.prompt = "What does len('cat') return?"

Nothing required the second . We solved the inconsistent-key problem but recreated a similar problem with incomplete .

To give every object its starting state during creation, a class can define a special named __init__. Continue with the Label example from the previous lesson:

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

Python calls __init__ when a new instance is created:

label = Label(
    "Question 1",
    "blue",
)

The two provide the starting values. Inside __init__, those values are stored as attributes on the new object. The exercise transfers this constructor pattern to Question.

For now, read self as “this instance.” We will examine it closely after the class has another method.

One class, several objects

The same class can create many independent instances:

first = Label("Question 1", "blue")
second = Label("Question 2", "green")

Both objects have the same type and the same attribute names. Their attribute values can differ.

One Label class creates two independent instances, each with its own text and color.

What does this print?

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

first = Label("Question 1", "blue")
second = Label("Question 2", "green")
print(first.color)
print(second.color)

Requiring constructor arguments does not validate every possible . It does make every normally constructed object start with the same dependable attributes. Chapter 5 will add stronger rules for valid state.

Task

Complete __init__ so every new question stores its own prompt and answer.

Run the program. You should see the first prompt and the second answer on separate lines.