Menu
CoddyTech

Câu hỏi nhiều lựa chọn

Bài học 6 trên 11 trong khóa học Dự án Python OOP: tạo trắc nghiệm của Coddy.

challenge icon

Thử thách

Trung bình

Tạo lớp MultiOptionsQuestion kế thừa từ Question, triển khai hàm khởi tạo và các phương thức print và check của lớp Question.

 

Hàm khởi tạo (constructor): nhận một chuỗi (string), một danh sách (list) các chuỗi và một số nguyên, rồi lưu chúng lần lượt vào các trường question, options  và answer_index.

 

Phương thức print: in câu hỏi theo định dạng sau:

[?] {question}

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

Ví dụ, nếu câu hỏi là 'How many states are in the USA?' và các lựa chọn là ['49', '50', '51', '32'],

[?] How many states are in the USA?

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

 

Phương thức check: trả về True nếu chuỗi đầu vào (câu trả lời) bằng answer_index + 1, nếu không thì trả về False.

Lưu ý: đầu vào của phương thức check là chuỗi, bạn cần chuyển nó thành số nguyên!

Tự làm thử

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

Tất cả bài học trong Dự án Python OOP: tạo trắc nghiệm

Tự luyện tập: Trình biên dịch Python online