我创建了一个应该在终端上运行的时钟程序。但每当我运行它时,它总是每秒将秒,分钟和小时增加1。
它应该每秒仅将秒增加1,直到秒为60,然后将分钟增加1等。
我不知道为什么它输出1:1:1然后2:2:2然后3:3:3等......
# Clock
import time
import sys
class Counter:
count = 0
name = ""
def __init__(self, name):
self.name = name
def Increment(self):
Counter.count += 1
def Reset(self):
Counter.count = 0
class Clock:
seconds = Counter("Seconds")
minutes = Counter("Minutes")
hours = Counter("Hours")
def Tick(self):
time.sleep(1)
Clock.seconds.Increment()
if Clock.seconds.count >= 60:
Clock.seconds.Reset()
Clock.minutes.Increment()
if Clock.minutes.count >= 60:
Clock.minutes.Reset()
Clock.hours.Increment()
if Clock.hours.count >= 12:
Clock.ResetClock()
def ResetClock(self):
Clock.seconds.Reset()
Clock.minutes.Reset()
Clock.hours.Reset()
def SetClock(self, seconds, minutes, hours):
self.hours = hours
self.minutes = minutes
self.seconds = seconds
def ReadClock(self):
sys.stdout.writelines(" \r Current Time: %d:%d:%d" % (Clock.hours.count, Clock.minutes.count, Clock.seconds.count))
clock = Clock()
while True:
clock.Tick()
clock.ReadClock()
答案 0 :(得分:3)
您的Counter
类中有类级变量而不是实例级变量。这意味着变量count
在您的类之间共享,这就是每当调用Increment
时它会递增的原因。
您应该count
成为实例的一部分而不是类:
class Counter:
def __init__(self, name):
self.name = name
self.count = 0
def Increment(self):
self.count += 1
def Reset(self):
self.count = 0