
当你在终端中看到类似 <Question object at 0x...> 的输出时,说明你直接打印了对象实例本身,而非其有意义的属性(如 text),本文将教你两种专业、可复用的解决方案。
当你在终端中看到类似 `
这个问题的根本原因在于:Python 默认调用对象的 __repr__ 方法来生成字符串表示,而未自定义该方法的类会返回形如 <module.Class object at 0x...> 的内存地址信息。在你的 QuizBrain.next_question() 方法中,current_question 是一个 Question 实例,但你直接将其用于 f-string 插值——即 f"{current_question}",这等价于 str(current_question),而由于 Question 类未定义 __str__ 或 __repr__,因此显示的是默认的内存地址。
✅ 解决方案一:显式访问属性(推荐初学者使用)
修改 QuizBrain.next_question() 方法,明确引用 Question 实例的 .text 属性:
def next_question(self):
current_question = self.question_list[self.question_number]
self.question_number += 1
user_answer = input(f"{self.question_number}: {current_question.text} (True/False): ")
# 注意:此处需补充 check_answer 调用,否则答案不会被验证
self.check_answer(user_answer, current_question.answer)⚠️ 重要提醒:原始代码中 next_question() 方法缺少对 check_answer() 的调用,导致用户输入后无反馈。务必补上(如上所示),否则逻辑不完整。
✅ 解决方案二:为 Question 类添加 __str__ 方法(更优雅、可扩展)
在 question_model.py 中的 Question 类内添加 __str__ 方法:
立即学习“Python免费学习笔记(深入)”;
class Question:
def __init__(self, text, answer):
self.text = text
self.answer = answer
def __str__(self):
return self.text添加后,所有涉及 str(question)、print(question) 或 f-string 中 {question} 的场景,都会自动返回 question.text,无需修改 QuizBrain 代码。这种方式符合 Python 的“约定优于配置”原则,提升代码可读性与复用性。
? 额外建议:增强健壮性
- 为防止 question_data 中字段缺失,可在 Question.__init__() 中加入参数校验:
if not isinstance(text, str) or not isinstance(answer, str): raise TypeError("Question text and answer must be strings") - 在 input() 前添加空格或换行,提升交互体验:
user_answer = input(f"\n{self.question_number}: {current_question.text} (True/False): ").strip()
两种方案均可彻底解决内存地址显示问题。初学阶段建议先用方案一,理解数据流向;进阶后推荐方案二,让类具备语义化表达能力——这是编写可维护 Python 代码的关键习惯。


















