鱼C论坛

 找回密码
 立即注册
查看: 3794|回复: 0

[学习笔记] python 44课,修改了计时器

[复制链接]
发表于 2018-2-28 00:00:07 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. import time

  2. class Mytimer:
  3.     def __init__(self):
  4.         self.begin,self.end=0,0
  5.         self.result=[]
  6.         self.unit=['年','月','日','时','分','秒']
  7.         self.total=[0,12,31,24,60,60]
  8.         self.prompt='请输入start()开始计时'

  9.     def __str__(self):
  10.         return self.prompt

  11.     __repr__=__str__

  12.     def __add__(self,other):
  13.         prompt='总时间是'
  14.         for i in range(6):
  15.             self.result[i]=self.result[i]+other.result[i]
  16.             if self.result[i]>self.total[i]:
  17.                 self.result[i]-=self.total[i]
  18.                 self.result[i-1]+=1
  19.                
  20.         for i in range(6):  #因为进位是后进的,所以如果进位前是0的话,并不会打印这一位,所以要再循环一次
  21.             if self.result[i]:
  22.                 prompt+=str(self.result[i])+self.unit[i]
  23.         print(prompt)
  24.                     
  25.     def start(self):
  26.         print('计时开始...')
  27.         self.begin=time.localtime()
  28.         self.prompt='请输入stop()结束计时'

  29.     def stop(self):
  30.         if not self.begin:
  31.             print('请输入start()开始计时')
  32.         else:
  33.             print('计时结束...')
  34.             self.end=time.localtime()
  35.             self.__calc()

  36.     def __calc(self):
  37.         self.prompt='共运行了'
  38.         self.result=[]  #重置列表
  39.         for i in range(6):
  40.             self.result.append(self.end[i]-self.begin[i])

  41.         for i in range(6):    #如果result出现负数,则向前借一位
  42.             if self.result[-1-i]<0:
  43.                 self.result[-1-i-1]-=1
  44.                 self.result[-1-i]+=self.total[-1-i]
  45.             if self.result[i]:
  46.                 self.prompt+=str(self.result[i])+self.unit[i]

  47.         self.begin,self.end=0,0
  48.         
  49. t1=Mytimer()
  50. t2=Mytimer()
复制代码


忽略月份大小的问题
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-14 14:14

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表