我正在尝试学习如何自动将类的所有成员编译到列表中。这段代码不是真实项目的一部分,只是一个帮助我解释我的目标的示例。我似乎找不到任何这方面的阅读 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_01
到 question_100
变量。当你想要重新排列问题的顺序,或者删除一个问题,或者在中间添加一个问题时,你会遇到麻烦。当您想在 question_02
和 question_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/