Python调用QuizBrain类next_question方法报AttributeError属性不存在问题
报错原因
你在next_question方法内定义的current_question是仅在方法内部生效的局部变量,没有绑定到类的实例对象上。你后续在f字符串中使用self.current_question取值时,实例本身不存在这个属性,因此抛出AttributeError。
修复方案
两种方案可按需选择:
- 方案1:直接使用已定义的局部变量,删除
self.前缀即可,适合不需要在其他方法中调用当前题目的场景
修改后的对应代码行:
user_input = input(f"Q.{self.question_number} : {current_question} (True/False) : ")
- 方案2:如果后续其他类方法也需要调用当前题目,将
current_question绑定为实例属性即可
修改next_question方法对应代码:
def next_question(self): self.current_question = self.question_list[self.question_number] self.question_number += 1 user_input = input(f"Q.{self.question_number} : {self.current_question} (True/False) : ")
内容的提问来源于stack exchange,提问作者Mrigankar Sonowal
相关产品推荐
相关产品推荐

