Your First Classes and Objects · practice
Create Valid Question Instances
The first Question class gave us a new kind of
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
To give every object its starting state during creation, a class can define a special __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 __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.

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
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.