如何自定义Python MultipleChoice类的__str__方法输出带编号选项
解决方案
你想要把遍历逻辑拆分到单独方法的思路是可行的,以下是可直接运行的修正代码:
class MultipleChoice: # 构造方法 def __init__(self, question, alternatives, correct_answer): self.question = question self.alternatives = alternatives self.correct_answer = correct_answer # 单独封装候选项格式化逻辑 def _format_alternatives(self): option_list = [] # 序号从1开始遍历候选项 for seq, option in enumerate(self.alternatives, start=1): option_list.append(f"{seq} - {option}") return "\n".join(option_list) def __str__(self): return f"{self.question}\n{self._format_alternatives()}" if __name__ == '__main__': question1 = MultipleChoice('What´s best?', ['Mac', 'PC'], 1) question2 = MultipleChoice('Biggest city in England?' , ['Manchester','Liverpool', 'London'], 3) print(question1) print(question2)
如果之前调用自定义方法失败,大概率是方法定义、或者调用时的拼写问题,上述代码里的私有方法调用逻辑完全符合Python语法,运行后输出完全匹配预期效果:
What´s best? 1 - Mac 2 - PC Biggest city in England? 1 - Manchester 2 - Liverpool 3 - London
如果不需要拆分方法,也可以直接把格式化逻辑写在__str__里,不过拆分的写法可读性更高,后续要调整候选项的展示格式时也更方便修改。
内容的提问来源于stack exchange,提问作者jjberg
相关产品推荐
相关产品推荐

