首页 > 解决方案 > 类计数器初始化

问题描述

这就是模板所说的:

def __init__(self):
    ## Initialize the instance variable that represents the count 

我写道:

class Counter:
def __init_(self):
    self.__count = 0
def get_count(self):
    return self.__count
def increment(self):
    return self.__count == self.__count+ 1
def set_count(self, value):
    self.value = 0

import Counter
def main():
  # The following causes the constructor to be invoked:  __init__()
  score_counter = counter.Counter()  
  print(score_counter.get_count())   # Display the current value of counter
  for points in range(10):           # Increment the counter 10 times
    score_counter.increment()
  score_counter.set_count(100)       # Set counter to 100
  print(score_counter)               # Displays str representation of counter `

'count' 应该递增 0 以此类推,但它永远保持为 0。

我必须为__init__部分写什么?

标签: pythonpython-3.x

解决方案


问题是你的increment-function。它不会增加__count- 变量,而是检查是否self.__count等于self.__count+ 1并返回答案(即TrueFalse

要解决此问题,请更改

return self.__count == self.__count+ 1

self.__count = self.__count+ 1

推荐阅读