2016-11-24 106 views
1

簡單的問題,但不能解決我的生活。我在問瑣事問題,但我想跟蹤正確的答案,所以我做一個計數器。如果不將它重置爲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

拋開你的代碼,並拿出你可以產生相同類型的錯誤的最小的例子。給出預期的行爲和實際行爲,並描述爲什麼你不能理解這種差異。瞭解如何創建[mcve]。 –

+2

會做配偶。讚賞。 –

+0

每場比賽只有一名球員,還是多名球員?如果有多個玩家,「計數」與每個玩家相關聯,而不是與問題有關。順便說一句,'.ask'中'for'循環的縮進被打破了。 –

回答

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 
+0

是否有助於將所有問題添加到課程中,然後定義訪問這些問題的方法? –

+1

有許多不同的方向來採取設計。你可以讓問題返回得分的數量。然後你可以總結一個循環。 –