Menu
CoddyTech

输出结果

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

我们来处理测验结果,并将其打印出来。

challenge icon

挑战

中等

在 Quiz 类中编写一个 print_results 方法,接收布尔值列表作为输入(True 表示第 i 个问题回答正确),并按照指定格式输出结果。

查看测试用例,了解格式!

亲手试试

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


class MultiOptionsQuestion(Question):
    def __init__(self, question, options, answer_index):
        self.question = question
        self.options = options
        self.answer_index = answer_index

    def print(self):
        print('[?] ' + self.question)
        print()
        for i in range(len(self.options)):
            print('[' + str(i + 1) + '] ' + self.options[i])
    
    def check(self, answer):
        return self.answer_index == int(answer) - 1


class Quiz:
    def __init__(self, questions):
        self.questions = questions
    
    def start(self):
        for question in self.questions:
            question.print()
            print()
            res = question.check(input('[+] '))
            print()
            print()

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

自己练习: Python 在线编译器