Menu
CoddyTech

多项选择题

Coddy 测验生成器:Python 面向对象项目 课程的第 6 课,共 11 课。

challenge icon

挑战

中等

创建一个类 MultiOptionsQuestion,使其继承自 Question,并实现 Question 类中的构造函数以及 print 和 check 方法。

 

构造函数:应接收一个字符串、一个字符串列表和一个整数,并依次将它们保存到字段 question、options 和 answer_index 中。

 

print 方法:按以下格式打印问题,

[?] {question}

[1] {options[0]}
[2] {options[1]}
.
.
.

例如,如果问题是 'How many states are in the USA?',选项是 ['49', '50', '51', '32'],

[?] How many states are in the USA?

[1] 49
[2] 50
[3] 51
[4] 32

 

check 方法:如果输入字符串(答案)等于 answer_index + 1,则返回 True,否则返回 False。

注意,check 方法的输入是字符串,你必须将它转换为整数!

亲手试试

from abc import ABC, abstractmethod


class Question(ABC):
    @abstractmethod
    def print(self):
        pass

    @abstractmethod
    def check(self, answer):
        pass


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

    def print(self):
        print('[?] ' + self.question + ' (yes/no)')
    
    def check(self, answer):
        return (answer == 'yes' and self.answer) or \
            (answer == 'no' and not self.answer)


class OpenQuestion(Question):
    def __init__(self, question, answers):
        self.question = question
        self.answers = answers

    def print(self):
        print('[?] ' + self.question)
    
    def check(self, answer):
        return answer in self.answers

测验生成器:Python 面向对象项目中的所有课

自己练习: Python 在线编译器