如何在Python 3的Question类中添加name、text、points变量?
给Python 3的Question类添加标签、问题文本和分值的实现方案
嘿,我来帮你搞定这个需求!要给Question类添加name(标签)、text(问题文本)和points(分值)这三个变量,最规范的方式是给类加个构造方法__init__,用来初始化这些实例属性——这样创建题目对象时既能直接设置属性,后续修改也很方便。
具体修改步骤
首先给原本空的Question类补上构造方法,还可以给参数设置默认值,让使用更灵活:
class Question: def __init__(self, name="", text="", points=0): self.name = name # 标签 self.text = text # 问题文本 self.points = points # 分值
完整修改后的代码
结合你提供的现有代码,修改后的完整版本如下:
class Question: def __init__(self, name="", text="", points=0): self.name = name self.text = text self.points = points class Multiple_Choice(Question): # 可以添加选择题特有的属性/方法,比如选项、正确答案 def __init__(self, name="", text="", points=0, options=None, correct_answer=""): # 调用父类构造方法,复用通用属性的初始化逻辑 super().__init__(name, text, points) self.options = options if options is not None else [] self.correct_answer = correct_answer def menu(): print('命令:') print('m - 添加选择题') print('p - 为题目添加分值') print('r - 为题目添加正确答案') print('t - 打印试卷') print('q - 退出') def main(): print('神奇的测验数据库!') # 举个使用例子:创建一道选择题实例 math_q = Multiple_Choice( name="数学选择题001", text="2+3等于多少?", points=5, options=["A.4", "B.5", "C.6"], correct_answer="B" ) # 打印属性验证效果 print(f"标签:{math_q.name}") print(f"问题:{math_q.text}") print(f"分值:{math_q.points}") if __name__ == '__main__': main()
简单说明
Question类的__init__方法给三个参数都设了默认值,所以即使不传参数也能创建实例,之后随时可以修改属性(比如question.points = 10)。- 继承自
Question的Multiple_Choice类,通过super().__init__()调用父类构造方法,复用了标签、问题文本和分值的初始化逻辑,同时能扩展选择题特有的属性。 main函数里加了个使用示例,你直接运行代码就能看到效果。
内容的提问来源于stack exchange,提问作者Zoboomafoo
相关产品推荐
相关产品推荐

