python - 将 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.
解决方案
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")),
...
]
推荐阅读
- sapui5 - 控制器的 onExit 事件中的元数据不可用 (?)
- ios - 使用 performSegue 时出现奇怪的转换行为
- groovy - 在 camunda dmn 的规则表的输出块中编写代码时如何在 groovy 中转义 $ 符号
- java - 将带有附加节点的 XML 转换为 Java 对象
- java - 调用 api 时出错(类型=不可接受,状态=406)
- android - 带有 RecyclerView Android 的动态标签
- javascript - moment.isoWeekday 不是函数
- css - 不能将 div 排列在另一个之下
- python - 如何将时空数据重塑为 lstm 输入?
- xpages - 通过复合数据上的 getComponent 获取价值