首页 > 解决方案 > 将 Python 类对象编译成列表

问题描述

我正在尝试学习如何将一个类的所有成员自动编译到一个列表中。这段代码不是真实项目的一部分,只是帮助我解释我的目标的一个例子。我似乎找不到任何关于此的阅读材料,我什至不知道这是否可能。提前感谢您的回答!=)

class question:
    def __init__(self,question,answer,list_of_answers):
        self.question=question
        self.answer=answer
        self.list_of_answers=list_of_answers

question_01=question('''
Which of these fruits is red?
A). Banana
B). Orange
C). Apple
D). Peach
''',"C",("A","B","C","D"))

question_02=question('''
Which of these is both a fruit and a vegetable?
A). Cauliflower
B). Tomato
C). Brocolli
D). Okrah
''',"B",("A","B","C","D"))

'''My objective is to write code that can automatically compile my questions (the
members of my question class) into a list,even if I have hundreds of them, without
having to manually write them into a list.'''

#If there are only two questions, final output should automatically become:
all_questions=[question_01,question_02]

#If there are one hundred questions, final output should automatically become:
all_questions=[question_01,question_02, ... ,question_99,question_100]

#Without having to manually type all of the one hundred questions (or members
#of the question class) to the list.

标签: pythonlistclassoop

解决方案


question_01首先,您不应该有 100 个question_100变量。当您想要重新排列问题、删除一个问题或在中间添加一个问题时,您会遇到麻烦。question_02当您想在and之间放置一个新问题时,您真的要重命名 98 个变量question_03吗?

此时,您应该强烈考虑将问题放入与源代码分开的数据文件中,并从文件中读取问题。但是,即使您不这样做,您也应该消除编号变量。将问题放在列表中开始。(此外,类应以 CamelCase 命名):

questions = [
    Question('''
Which of these fruits is red?
A). Banana
B). Orange
C). Apple
D). Peach
''', "C", ("A","B","C","D")),
    Question('''
Which of these is both a fruit and a vegetable?
A). Cauliflower
B). Tomato
C). Brocolli
D). Okrah
''', "B", ("A","B","C","D")),
    ...
]

推荐阅读