Câu hỏi mở
Bài học 5 trên 11 trong khóa học Dự án Python OOP: tạo trắc nghiệm của Coddy.
Thử thách
DễTạo một lớp (class) OpenQuestion kế thừa từ Question, rồi 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 - nhận một chuỗi và một danh sách chuỗi, rồi lần lượt lưu chúng vào các trường question và answers.
Phương thức print - in câu hỏi theo định dạng '[?] {question}'
Ví dụ, nếu câu hỏi là 'Are you experienced programmer?', phương thức sẽ in '[?] Are you experienced programmer?'
Phương thức check - trả về True nếu chuỗi đầu vào (câu trả lời) có trong trường answers, nếu không thì trả về False.
Ví dụ, với answers = ['yes', 'maybe'], nếu check('yes') thì trả về True, còn nếu check('nope') thì trả về False
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)
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