Python将对象创建附加到另一个类中的列表

时间:2017-11-02 13:21:25

标签: python

为什么不将对象添加到列表中?我通过添加自我等来测试。 .questionlist.append(self)

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')

1 个答案:

答案 0 :(得分:1)

要回答您的实际问题,您只需要Quiz.questionlist.append(self),因为Quiz 是具有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()

一般规则是,一个最多有两个方法的类,其中一个是__init__,应该只是一个函数。 Quiz符合条件,因此只需定义一个返回Questions列表的函数即可。等到你有几个这样的函数(添加到现有列表,或删除问题等)之后再考虑创建一个Quiz类来封装问题列表。