这是「Python 100 天」系列第 17 天的学习笔记:用类组织程序:答题 Quiz 。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。
今天要解决的问题
把 12 道判断题做成问答程序:逐题提问、判分、最后公布总分。README 知识点:创建类、属性、__init__ 构造方法、给类加方法——以及"为什么 OOP 值得" 。
一、三个类,三种职责
1 2 3 Question —— 一道题:题干 + 正确答案 QuizBrain —— 出题器:题库、当前题号、得分、判分逻辑 main.py —— 胶水:组装对象、跑循环
职责分开之后,每块都能单独测试:Question 只存数据,QuizBrain 只处理流程,main 只负责串起来。这就是 OOP 最实际的好处——改一处不影响其它处 。
二、对象列表
1 2 3 4 question_bank = [] for question in question_data: new_question = Question(question['text'], question['answer']) question_bank.append(new_question)
question_data 是"字典列表"(原始数据),question_bank 是"对象列表"(领域模型)。这一步叫数据建模 :把外部格式转成程序里好用的形状。
三、方法之间互相调用
QuizBrain.next_question() 里调用了 self.check_answer(...)。类内部调用自己的方法必须带 self.,否则会去找一个同名的全局函数,报 NameError。
代码全文
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 # ============================================================ # day17/main.py —— 答题程序入口(面向对象版) # 作用:把 data.py 的字典数据转换成 Question 对象,交给 QuizBrain 一题题问。 # 知识点:import、列表推导之外的“for + append”建对象流程、 # 对象列表、用方法返回值当 while 条件 # ============================================================ from question_model import Question from data import question_data from quiz_brain import QuizBrain # 空列表当“题库容器”,准备装 Question 对象(不是字典)。 question_bank = [] # 遍历原始数据(每条是字典)。 for question in question_data: # 用键取名:字典['text'] / 字典['answer'] question_text = question['text'] question_answer = question['answer'] # 创建 Question 对象。这一步是“数据 → 对象”的转换, # 转换之后,后面所有代码都只跟 .text / .answer 打交道,不再关心字典结构。 new_question = Question(question_text, question_answer) question_bank.append(new_question) # 把题库交给控制器。QuizBrain 内部会保存这个列表并把题号、分数归零。 quiz = QuizBrain(question_bank) # 只要还有题就一直问:still_has_questions() 返回布尔值,直接当循环条件。 # 这是“把判断封装进方法”的好处——主程序读起来就是一句人话。 while quiz.still_has_questions(): quiz.next_question() # 注意:next_question 内部会改 quiz 的题号和分数, # 所以每轮循环的状态都在变,不会死循环。 # 结束后从 quiz 对象上取最终成绩。 print(f"Thanks for completing that!nYour final score is: {quiz.score}/{quiz.question_number}")
question_model.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 # ============================================================ # day17/question_model.py —— 题目类 # 作用:把“一道判断题”封装成对象,只留两个属性。 # 知识点:最小可用类、__init__、self # ============================================================ class Question: # 构造方法:创建 Question 对象时,把题干和答案存到这个对象上。 # 参数 text :题干字符串(str) # 参数 answer:标准答案字符串("True" / "False") # 返回值:None(构造函数不能返回别的东西) def __init__(self, text, answer): # self.text / self.answer 就是“实例属性”, # 之后 quiz_brain 里用 question.text、question.answer 取值。 # 这个类故意不写任何方法:它的职责只是“装数据”, # 判断对错、计分交给 QuizBrain——单一职责。 self.text = text self.answer = answer
quiz_brain.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 # ============================================================ # day17/quiz_brain.py —— 答题控制器 # 作用:管理“当前第几题、得了多少分”,负责出题、判分、打印进度。 # 知识点:类的三个状态属性、方法之间互相调用、len()、字符串 lower()、 # 用“返回值是布尔”的方法当循环条件 # ============================================================ class QuizBrain: # 构造方法。 # 参数 question_list:Question 对象组成的列表(题库) # 三个实例属性就是这个控制器的全部状态: # question_number —— 已经出了几题(同时充当下标) # question_list —— 题库 # score —— 答对了几题 def __init__(self, question_list): self.question_number = 0 self.question_list = question_list self.score = 0 # 还有没有题? # 无参数;返回值:True 还有 / False 做完了 # 注意:这里“比较”的结果本身就是一个布尔值,所以直接 return 它, # 不需要写 if ...: return True else: return False。 def still_has_questions(self): return self.question_number < len(self.question_list) # 出下一题:取题 → 题号 +1 → 问用户 → 判分。 # 无参数;无返回值(副作用是改状态 + 打印)。 def next_question(self): # 用题号当列表下标取当前题。题号从 0 开始,所以第一次取第 0 题。 current_question = self.question_list[self.question_number] # 先 +1 再提问,这样提示里显示的是 Q.1、Q.2……(人类习惯从 1 数)。 self.question_number += 1 # current_question.text 是 Question 对象的属性 user_answer = input(f"Q.{self.question_number}: {current_question.text} (True/False)") # 把活交给 check_answer,自己不再判断——职责分离。 self.check_answer(user_answer, current_question.answer) # 判分并打印。 # 参数 user_answer :用户输入的字符串 # 参数 correct_answer:正确答案字符串 # 无返回值 def check_answer(self, user_answer, correct_answer): # str.lower():无参数,返回全小写的新字符串。 # 两边都转小写,用户输入 true / TRUE / True 都算对。 if user_answer.lower() == correct_answer.lower(): print("You got it right!") self.score += 1 else: print("That's incorrect") print(f"The correct answer was: {correct_answer}.") # 进度显示用 self.question_number(已出题数),分母是总题数。 print(f"Your current score is {self.score}/{self.question_number}.") print("n")
题库 data.py(节选)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 # ============================================================ # day17/data.py —— 题库数据 # 作用:只存数据,不写逻辑。question_data 是一个“字典列表”。 # 知识点:列表 + 字典的常见组合、字符串的隐式拼接 # ============================================================ # 每一道题就是一个字典,两个键固定: # "text" —— 题干(str) # "answer"—— 答案("True" / "False",注意是字符串不是布尔值) # 外层用列表装起来,顺序就是出题顺序。 question_data = [ {"text": "A slug's blood is green.", "answer": "True"}, {"text": "The loudest animal is the African Elephant.", "answer": "False"}, {"text": "Approximately one quarter of human bones are in the feet.", "answer": "True"}, {"text": "The total surface area of a human lungs is the size of a football pitch.", "answer": "True"}, # 相邻的两个字符串(中间只有空白或换行)Python 会自动拼成一个, # 所以下面这条其实是 "…take it home to eat." 一整句; # 长句拆行写、又不想用 + 拼接时,这个特性很方便。 {"text": "In West Virginia, USA, if you accidentally hit an animal with your car, you are free to take it home " "to eat.", "answer": "True"}, {"text": "In London, UK, if you happen to die in the House of Parliament, you are entitled to a state funeral." , "answer": "False"}, {"text": "It is illegal to pee in the Ocean in Portugal.", "answer": "True"}, {"text": "You can lead a cow down stairs but not up stairs.", "answer": "False"}, {"text": "Google was originally called 'Backrub'.", "answer": "True"}, {"text": "Buzz Aldrin's mother's maiden name was 'Moon'.", "answer": "True"}, {"text": "No piece of square dry paper can be folded in half more than 7 times.", "answer": "False"}, # 最后一条没有逗号也合法:列表末尾的逗号是可选的。 {"text": "A few ounces of chocolate can to kill a small dog.", "answer": "True"} ]
代码走读
Question.__init__(self, text, answer):两个属性,没有方法——它是纯粹的"数据类"。用 dataclass 可以一行写完(后面会讲)。
QuizBrain.__init__(self, question_list):question_number 从 0 开始(下一个要出的题的下标 ),score 从 0 开始。
still_has_questions():return self.question_number < len(self.question_list),返回布尔值,直接给 while 用。方法返回布尔值、调用处直接当条件 ,是很好的习惯。
next_question():取出当前题 → 题号 +1 → input 提问 → 交给 check_answer。注意题号先加再打印,所以显示是 Q.1 而不是 Q.0。
check_answer():两边都 .lower() 再比,避免大小写差异;对了加分;无论对错都打印正确答案和当前分数。
主程序 while quiz.still_has_questions(): quiz.next_question(),最后打印总分。
一个隐藏的小 bug
最后一行:
1 print(f"... {quiz.score}/{quiz.question_number}")
question_number 在最后一题时已经加到 12,所以显示 x/12 是对的。但如果中途 break,分母就会偏大——用"已答题数"当分母 更稳,可以单独维护一个 answered 计数。
运行示例
1 2 3 4 Q.1: A slug's blood is green. (True/False)True You got it right! The correct answer was: True. Your current score is 1/1.
易错点
self.question_number 忘了 self. :报 NameError 或 UnboundLocalError。
题库为空 :still_has_questions() 返回 False,循环一次都不进,这是正确行为。
大小写/空格 :"true " 带空格会判错,可以 .strip().lower()。
把 Question 写成字典 :也能跑,但失去了"对象有方法"的扩展性(比如以后加 hint())。
动手改
加 shuffle 打乱题目顺序(random.shuffle(question_bank))。
加错题本:答错时把 Question 存进列表,结束后重做。
用 @dataclass 重写 Question,对比代码量。
源文件逐个讲解
5 个文件 ,四个 .py 里三个是类、一个是数据。
文件
行数
职责
data.py17 12 道判断题
question_model.py6 Question 类
quiz_brain.py27 QuizBrain 类:出题、判分、记分
main.py18 组装:把字典变成对象
README.md8 说明页
data.py(17 行)
1 2 3 4 5 question_data = [ {"text": "A slug's blood is green.", "answer": "True"}, {"text": "The loudest animal is the African Elephant.", "answer": "False"}, ... ]
12 个字典,每个只有 text 和 answer 两个键 ,answer 是字符串 "True"/"False",不是布尔值。这一点很关键——后面比较时要用 .lower() 统一大小写。
注意第 5 条和第 6 条用了字符串隐式拼接 :
1 2 {"text": "In West Virginia, USA, if you accidentally hit an animal with your car, you are free to take it home " "to eat.", "answer": "True"},
两个相邻字符串字面量会自动拼成一个 ,这是 Python 的语法糖,用来在源码里换行写长字符串(不用 )。
question_model.py(6 行)
1 2 3 4 5 class Question: def __init__(self, text, answer): self.text = text self.answer = answer
全书最短的类 :只有 __init__,两个属性。它的价值不在代码,而在「把字典变成有类型的对象」 :
用字典:q["text"],拼错了不报错(运行到才知道);
用对象:q.text,拼错立刻 AttributeError。
这就是「模型类(model)」的雏形 ——Day 63 的 SQLAlchemy 模型是同一个思路,只是多了数据库映射。
quiz_brain.py(27 行)
1 2 3 4 5 class QuizBrain: def __init__(self, question_list): self.question_number = 0 self.question_list = question_list self.score = 0
三个实例属性 :当前题号、题库、得分。状态全部挂在对象上 ,所以不需要 global,也不怕开两份 quiz。
1 2 def still_has_questions(self): return self.question_number < len(self.question_list)
「还有题吗」写成方法而不是属性 ,返回布尔值,让主循环写成 while quiz.still_has_questions():——读起来像英语。如果用 question_number < len(...) 直接写在 while 里,主程序就得知道 QuizBrain 的内部结构 ,这就是封装的意义。
1 2 3 4 5 def next_question(self): current_question = self.question_list[self.question_number] self.question_number += 1 user_answer = input(f"Q.{self.question_number}: {current_question.text} (True/False)") self.check_answer(user_answer, current_question.answer)
先取题、再把题号 +1、再用新题号打印 ——顺序是刻意的,这样第一题显示 Q.1 而不是 Q.0。
next_question 同时做了三件事 :取题、问人、判分。「问」和「判」本可以分开 (check_answer 已经是独立方法了,但 input 还在 next_question 里)。Day 34 用 Tkinter 重写时,就把 input 换成了 GUI 回调——那时这个设计会显得不够灵活。
1 2 3 4 5 6 7 8 9 def check_answer(self, user_answer, correct_answer): if user_answer.lower() == correct_answer.lower(): print("You got it right!") self.score += 1 else: print("That's incorrect") print(f"The correct answer was: {correct_answer}.") print(f"Your current score is {self.score}/{self.question_number}.") print("n")
.lower() 两边都调 ,所以 true、TRUE、True 都算对。.strip() 没加 ,输入 "true "(带空格)会判错——这类小坑很常见。
self.score 在类内部自增 ,外部只读(quiz.score),这是「谁的数据谁维护」。
main.py(18 行)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 from question_model import Question from data import question_data from quiz_brain import QuizBrain question_bank = [] for question in question_data: question_text = question['text'] question_answer = question['answer'] new_question = Question(question_text, question_answer) question_bank.append(new_question) quiz = QuizBrain(question_bank) while quiz.still_has_questions(): quiz.next_question() print(f"Thanks for completing that!nYour final score is: {quiz.score}/{quiz.question_number}")
「数据转换」这一步单独写在 main.py 里 ,而不是塞进 QuizBrain.__init__。好处是 QuizBrain 只认 Question 对象,不认字典 ——数据源换成 API(Day 34)时,只改 main.py 的转换段,quiz_brain.py 一行不用动。
最后一行直接读 quiz.score 和 quiz.question_number ,两个属性都是公开的。
循环结束后 question_number 正好等于题数 (每答一题 +1),所以 12/12 能对上——这个巧合依赖 next_question 里的 += 1 位置,改代码时要小心 。
这份代码的问题
user_answer 没 .strip() :带空格判错。
check_answer 不返回对错 ,只打印——Day 34 的 GUI 版本必须知道结果才能显示 ✔/✘,那时就得改签名。
Question.answer 是字符串 ,如果数据里混进 "true"/"yes",比较逻辑全靠 .lower() 兜着。
README.md(8 行)
标题 Day 17 - The Quiz Project & the Benefits of OOP,知识点:How to create the Class、Working with Attributes、Working with Methods、the __init__() method、Class and Object。
这一天的标题里带「the Benefits of OOP」 ——四个文件正好演示了「一个类一个文件」的分工:数据、模型、业务、组装。
依赖关系
1 2 3 4 5 main.py ├── data.question_data (原始字典) ├── question_model.Question (字典 → 对象) └── quiz_brain.QuizBrain (对象 → 流程) ↑ 只依赖 Question 的 .text / .answer
quiz_brain.py 没有 import question_model ——它只要求传进来的对象有 .text 和 .answer。又一次鸭子类型。