我有一个名为Question的课程,如下所示
class Question:
q_count = 0
def __init__(self, s_id, q_id, question):
print("q count is ", Question.q_count)
self._s_id = s_id
self._question_text = question
self._answers = []
self._q_id = Question.q_count
def get_answers(self):
return self._answers
def set_answers(self,answers):
self._answers = answers
def add_answer(self, Answer()):
self._answers.append(Answer())
我希望它有一个名为_answers的列表,它是一个Answer对象列表。答案是我创建的另一种类型。
class Answer:
def __init__(self, q_id, a_id):
self._q_id = q_id
self._a_id = a_id
# Subclass for multiple choice
class MC_Answer(Answer):
def __init__(self, q_id, a_id, answer_text):
Answer.__init__(self, q_id, a_id)
self._answer_text = answer_text
def get_answer_text(self):
return self._answer_text
def set_answer_text(self, a_id):
self._a_id = a_id;
在我的代码的另一部分中,我正在创建一个MC_Answer对象的实例。我还有一个问题对象的实例。如何将其附加到答案列表中?
answer1 = MC_Answer(idQ, 1, answer_text)
new_q.add_answer(answer1)
write_to_file(alist1, "answers.csv")
这是错误的,但如果我没有将answer1作为参数,那么Python如何知道添加该特定答案的实例?
答案 0 :(得分:0)
您的添加答案类从不使用参数,而是创建Answer类的新实例并将其附加到列表中,而是需要修改它以为其提供参数然后正确使用
def add_answer(self, Answer()):
self._answers.append(Answer())
应该是
def add_answer(self, answer):
self._answers.append(answer)