在 class 中设置计数器的问题

Issue with setting a counter inside a class

简单的问题,但我一辈子都弄不明白。我在问琐事问题,但我想跟踪正确答案,所以我做了一个反击。如果不将其重置为 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()

问题是每个 Questions class 实例化都有单独的实例数据。您可以改用 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 可以通过拥有 class 成员而不是实例成员数据来共享数据:

class Question():
    count = 0

    def ask(self):
        self.count += 1
        print(self.count)

>>> a = Question()
>>> a.ask()
1
>>> b = Question()
>>> b.ask()
2

编辑:如果你想完全分开分数,你可以得到 ask return 分数,然后将它们相加。每个问题也可能值得不同的分数:

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