You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Quiz游戏开发问题:输出对象内存地址而非问题文本

问题解决:Quiz游戏输出对象内存地址而非问题文本

你看到的<question_model.Question object at 0x00000186F100FE80>是Python默认的对象字符串表示,原因是直接将Question类的实例插入字符串时,该类未定义可读的字符串转换逻辑,或是你没有访问实例的具体属性。

解决方法一:直接访问Question实例的text属性

修改QuizBrain类的next_question方法,直接调用Question对象存储问题文本的属性(假设属性名为text,如果你的类里用了其他命名比如question_text,对应替换即可):

def next_question(self):
    current_question = self.question_list[self.question_number]
    self.question_number += 1
    input(f"Q.{self.question_number}: **{current_question.text}** (True / False): ")

解决方法二:给Question类添加__str__方法

在Question类中定义__str__方法,让Python在需要将对象转为字符串时自动返回问题文本:

class Question:
    def __init__(self, text, answer):
        self.text = text
        self.answer = answer

    def __str__(self):
        return self.text

之后再在f-string中使用{current_question}时,就会输出问题文本而非内存地址。

内容的提问来源于stack exchange,提问作者barak zak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 18:30:43