定义一个类描述数字时钟,要求:给定一个时间,例如15:50:00,则最终的效果为,如图:
import time # 导入时间模块 class Clock(object): def __init__(self, h, m, s): # 时间初始化 self.hour = h self.minute = m self.second = s def run(self): # 走字 self.second += 1 # 秒+ if self.second == 60: self.second = 0 self.minute += 1 if self.minute == 60: self.minute = 0 self.hour += 1 if self.hour == 24: self.hour = 0 def show(self): # 显示 print("%02d:%02d:%02d"%(self.hour,self.minute,self.second)) #不足两位的在数字前补0 def clocktime(): h = int(input("请输入小时")) m = int(input("请输入分钟")) s = int(input("请输入秒钟")) clock = Clock(h,m,s) while True: clock.show() time.sleep(1) clock.run() print(clocktime())
输出结果:
03:09:42 03:09:43 03:09:44 03:09:45 03:09:46 03:09:47 03:09:48 03:09:49 03:09:50 03:09:51 03:09:52 03:09:53 03:09:54 03:09:55