Python
Adding questions
Add questions with add_question.
The Quiz class manages the collection
Once you have a single Question instance, you need to collect them in a list. The Quiz class does this: it holds an empty list named questions and adds new questions through an add_question method.
The line questions: list = field(default_factory=list) gives every new Quiz instance its own empty list. Without default_factory=list, all instances would share the same list — a common bug.
The add_question method
The add_question method does one thing in a single line: self.questions.append(q). The self pseudo-variable refers to the instance itself, so the method can reach the questions list. To call it you write quiz.add_question(Question(...)); the dataclass instance is ready in one line.
After adding, len(quiz.questions) tells you how many questions the quiz has. This count is what you'll print to confirm the add worked.
Exercise Write the Quiz class and add_question method
The Question class above is ready. Now define a Quiz class with @dataclass; add the field questions: list = field(default_factory=list) and write def add_question(self, q): with the body self.questions.append(q). Then create quiz = Quiz(), add two questions and print the count with print(len(quiz.questions)).
Show example solution
from dataclasses import dataclass, field
@dataclass
class Question:
text: str = ""
answer: str = ""
@dataclass
class Quiz:
questions: list = field(default_factory=list)
def add_question(self, q):
self.questions.append(q)
quiz = Quiz()
quiz.add_question(Question(text="Capital?", answer="Ankara"))
quiz.add_question(Question(text="2x2?", answer="4"))
print(len(quiz.questions))
Test yourself
-
Complete the default of the questions field
@dataclass
class Quiz:
questions: list = field(default_factory=____)
def add_question(self, q):
self.questions.append(q)
Show answer
@dataclass
class Quiz:
questions: list = field(default_factory=list)
def add_question(self, q):
self.questions.append(q)
-
What does default_factory=list do?
- Returns the list type
- Fills list items automatically
- Shares one list across the class
- Produces a fresh empty list for each instance
Show answer
Produces a fresh empty list for each instance — default_factory=list gives every new instance its own empty list, avoiding the shared-list bug.
-
Match the Quiz class concepts
- questions
- Question list
- add_question
- Question-adding method
- len
- Count function
- self
- The instance itself
Next lesson: Running the quiz