python - 将 Python 类对象编译到列表中

标签 python list class oop

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

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.

最佳答案

您一开始就不应该有 100 个 question_01question_100 变量。当你想要重新排列问题的顺序,或者删除一个问题,或者在中间添加一个问题时,你会遇到麻烦。当您想在 question_02question_03 之间添加新问题时,您真的需要重命名 98 个变量吗?

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

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")),
    ...
]

关于python - 将 Python 类对象编译到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55230277/

相关文章:

java - 什么样的集合类来获取数组中的位置?

python - 谁能为 Python 推荐一个不错的 FOSS PDF 生成器?

python - 检查一个大文件 .csv 并替换,并将其分类在一列中

Python:带有间隙的切片的语法更短?

java - 奇怪的 Apache Commons Lang StringUtils.join 结果

python - 使用字符串搜索字典列表并将其附加到相同格式的另一个列表中

python - 峰值频率python的时间戳

javascript - 为什么类中的事件处理程序不从该类继承变量

java.lang.ClassFormat错误: Incompatible magic value 218774561

c++ - 模板元编程时struct和class的区别