Python将对象创建附加到另一个类中的列表
为什么不将对象添加到列表中?我一直在做测验。类。问题列表。通过添加自我等方式附加(自我)Python将对象创建附加到另一个类中的列表,python,Python,为什么不将对象添加到列表中?我一直在做测验。类。问题列表。通过添加自我等方式附加(自我) class Question: def __init__(self, question, answer): self.__question = question self.__answer = answer Quiz.__class__.questionlist.append(self) class Quiz: questionlist = [] def
class Question:
def __init__(self, question, answer):
self.__question = question
self.__answer = answer
Quiz.__class__.questionlist.append(self)
class Quiz:
questionlist = []
def __init__(self):
self.generateQuestion()
def generateQuestion(self):
q1 = Question('How many weeks are there in a year? [DMID Standard]', '52')
q2 = Question('Do cows drink milk?', 'y')
q3 = Question("Is the word 'madam' a palindrome?", 'y')
q4 = Question("Biggest search engine?", 'google')
q5 = Question('You are in a race. You run past the second guy. What position are you in?', 'second')
要回答实际问题,您只需要
quick.questionlist.append(self)
,因为quick
是具有questionlist
属性的类对象
不过,您可以在这里使用更简单、直接的设计
class Question(object):
def __init__(self, q, a)
self.question = q
self.answer = a
def make_quiz():
return [
Question('How many weeks are there in a year? [DMID Standard]', '52'),
Question('Do cows drink milk?', 'y'),
Question("Is the word 'madam' a palindrome?", 'y'),
Question("Biggest search engine?", 'google'),
Question('You are in a race. You run past the second guy. What position are you in?', 'second')
]
quiz = make_quiz()
一般规则是,一个最多有两个方法的类,其中一个是
\uuuu init\uuuu
,应该只是一个函数<代码>测验符合条件,因此只需定义一个函数,返回问题列表。在考虑创建一个测验
类来封装问题列表之前,请等待您拥有多个这样的函数(添加到现有列表中,或删除问题等)。根据您当前的缩进,问题
没有初始化
方法。测验
是一个类;你只需要quick.question\u list
。也就是说,如果你没有实际生成一个quick
类,你就不需要它了。一个以列表作为参数代替generateQuestion
的常规函数就足够了。为什么问题
需要知道它是测验的一部分?@chepner谢谢,但我需要使用测验类,因为这是我作业中所要求的。