这是模板的意思:
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 `
“计数”应以0递增,依此类推,但永远保持0。
__init__
部分我要写什么?
答案 0 :(得分:1)
问题是您的increment
功能。它不会递增__count
变量,而是检查self.__count
是否等于self.__count+ 1
并返回答案(即True
或False
)< / p>
要解决此问题,请更改
return self.__count == self.__count+ 1
到
self.__count = self.__count+ 1
答案 1 :(得分:0)
您要执行的操作的简单,干净的实现:
class foo:
def __init__(self):
self.count = 0
def get_count(self):
print(self.count)
return self.count
def increment_count(self):
self.count = self.count + 1
def main():
# Create the object
f = foo()
# Call the get_count function on the object
f.get_count() # OUTPUT: 0
# Increment the counter
f.increment_count()
# Call the get_count function on the object
f.get_count() # OUTPUT: 1
if __name__=="__main__":
main()
希望这会有所帮助