简单的问题,但不能为我的生活弄清楚。我问琐事问题,但我想跟踪正确答案,所以我做了一个反击。如果不将它重置为0或者过早引用错误,就无法确定放置的位置。
class Questions():
def __init__(self, question, answer, options):
self.playermod = player1()
self.question = question
self.answer = answer
self.options = options
self.count = 0
def ask(self):
print(self.question + "?")
for n, option in enumerate(self.options):
print("%d) %s" % (n + 1, option))
response = int(input())
if response == self.answer:
print("Correct")
self.count+=1
else:
print("Wrong")
questions = [
Questions("Forest is to tree as tree is to", 2, ["Plant", "Leaf", "Branch", "Mangrove"]),
Questions('''At a conference, 12 members shook hands with each other before &
after the meeting. How many total number of hand shakes occurred''', 2, ["100", "132", "145", "144","121"]),
]
random.shuffle(questions) # randomizes the order of the questions
for question in questions:
question.ask()
答案 0 :(得分:2)
问题是每个Questions
类实例化都有单独的实例数据。您可以使用class
属性来解决此问题。
基本上你有这个:
class Question():
def __init__(self):
self.count = 0
def ask(self):
self.count += 1
print(self.count)
如果您有两个不同的问题实例,他们将拥有自己的count
成员数据:
>>> a = Question()
>>> a.ask()
1
>>> a.ask()
2
>>> b = Question()
>>> b.ask()
1
您想要的是共享相同count
变量的两个问题。 (从设计的角度来看,这是可疑的,但我认为你是在尝试理解语言的技术性而不是面向对象的设计。)
Question
类可以通过拥有类成员而不是实例成员数据来共享数据:
class Question():
count = 0
def ask(self):
self.count += 1
print(self.count)
>>> a = Question()
>>> a.ask()
1
>>> b = Question()
>>> b.ask()
2
编辑:如果你想完全分开乐谱,你可以ask
返回积分然后总结。每个问题也可能值得不同点:
class Question():
def __init__(points):
self.points = points
def ask(self):
return self.points # obviously return 0 if the answer is wrong
>>> questions = [Question(points=5), Question(points=3)]
>>> sum(question.ask() for question in questions)
8