python - 在类中设置计数器的问题

标签 python class counter

简单的问题,但我一生都无法弄清楚。我正在问一些琐事问题,但我想跟踪正确答案,所以我做了一个计数器。只是无法确定将其放置在何处而不将其重置为 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 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

关于python - 在类中设置计数器的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40781239/

相关文章:

python - 解析器.add_argument : error: unrecognized arguments: True

python - 我收到错误 'except MySQLdb.error, e' 语法错误 - 尝试将我的 scrapy 蜘蛛写入 mysql 时语法无效,

python - Pandas Dataframe 的复杂子集

c++ - C++ 中类定义的顺序

python :getting the count for the adjectives in a string

python - GEE不将数据导入数组

c++ - 如何自动维护一个类实例列表?

模板化类对象的 C++ vector

javascript - 如何在 onClick 事件中增加计数器值?

python - 从 Counter 中删除最不常见的元素