【发布时间】:2023-03-10 10:45:01
【问题描述】:
我正在尝试学习如何将一个类的所有成员自动编译成一个列表。这段代码不是真实项目的一部分,只是帮助我解释我的目标的一个例子。我似乎找不到任何关于此的阅读材料,我什至不知道这是否可能。提前感谢您的回答! =)
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.
【问题讨论】:
-
为什么不创建一个列表并附加对象?
-
我认为“编译”这个词是正确的。
-
我可以假设您的输入是一个问题列表,例如: [q1, q2, ... q100] 其中 q1 = "这些水果中哪些是红色的?",q2 = "其中哪些是既是水果又是蔬菜?”等;和 [a1,a2, ... an] 其中 a1 =["Banana", "Orange", "Apple", "Peach"], ... 等等。不清楚您的输入和输出是什么.
-
@juanpa.arrivillaga 干得好!这对我来说是完美的!
-
@mm_ 实际上,我正在寻找一个作为输出的列表。基本上,我想告诉程序“取出属于这个特定类的每个对象,并从中列出一个列表。我可以按照 juanpa.arrivillaga 的建议分别附加每个对象,它会很好用,但我是还希望使用单个命令为该类创建所有对象的列表。=)