Kelvin Davis Kelvin Davis - 11 days ago 5
Python Question

Issue with setting a counter inside a class

Simple question, but cant figure it out for the life of me. I'm asking trivia question but i want to keep track of correct answers, so I make a counter. Just can't figure where to put without it being reset to 0 or getting a premature reference error.

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()

Answer

The problem is you have separate instance data per Questions class instantiation. You can solve this by using a class attribute instead.

Essentially you have this:

class Question():
    def __init__(self):
        self.count = 0

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

If you have two different question instances, they will have their own count member data:

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

What you want is both questions to share the same count variable. (from a design standpoint this is dubious, but I take it you're trying to understand the technicalities of the language rather than object oriented design.)

The Question class can share data by having a class member rather than instance member data:

class Question():
    count = 0

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

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

edit: If you wanted to completely separate the score you could have ask return the points and then sum them up. Each question could be worth a different amount of points, too:

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
Comments