python - 类计数器初始化
问题描述
这就是模板所说的:
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__
部分写什么?
解决方案
问题是你的increment
-function。它不会增加__count
- 变量,而是检查是否self.__count
等于self.__count+ 1
并返回答案(即True
或False
)
要解决此问题,请更改
return self.__count == self.__count+ 1
至
self.__count = self.__count+ 1
推荐阅读
- java - 关于@Service Spring Boot 中的@Spy 和@InjectMocks 的说明
- aws-appsync - 如何在 AppSync 突变上生成 Slug
- c# - 如何创建多个系列
- php - 如何在 PHP 中正确添加日期和时间(字符串)?
- javascript - 在事件处理程序中访问 React 组件参数
- c++ - [basic.start.main]/2 以“实现不应预定义主要功能”开头。这意味着什么?
- c++ - 将用户定义的数据类型保存到 C++ 中的文件
- python - 与 Pandas 组合 GPS 点
- html - 使用时 Ng-hide 不起作用标签在一起
- php - 我创建的数据库中的结果不会出现在 wordpress 中。