鱼C论坛

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

[学习笔记] A-23-类的简单定制

[复制链接]
发表于 2018-7-18 20:55:55 | 显示全部楼层 |阅读模式

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

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

x
  1. #coding= UTF-8


  2. import time as t

  3. class MyTimer:
  4.     def __init__(self):
  5.         self.unit = ['年', '月', '天', '小时', '分钟', '秒']
  6.         self.borrow = [0, 12, 31, 24, 60, 60]
  7.         self.prompt = "未开始计时!"
  8.         self.lasted = []
  9.         self.begin = 0
  10.         self.end = 0

  11.     def __str__(self):
  12.         return self.prompt

  13.     __repr__ = __str__

  14.     def __add__(self, other):
  15.         prompt = "总共运行了"
  16.         result = []
  17.         for index in range(6):
  18.             result.append(self.lasted[index] + other.lasted[index])
  19.             if result[index]:
  20.                 prompt += (str(result[index]) + self.unit[index])
  21.         return prompt

  22.     # 开始计时
  23.     def start(self):
  24.         self.begin = t.localtime()  #获取本地时间
  25.         self.prompt = "提示:请先调用 stop() 停止计时!"
  26.         print("计时开始...")

  27.     # 停止计时
  28.     def stop(self):
  29.         if not self.begin:
  30.             print("提示:请先调用 start() 进行计时!")
  31.         else:
  32.             self.end = t.localtime()
  33.             self._calc()
  34.             print("计时结束!")

  35.     # 内部方法,计算运行时间
  36.     def _calc(self):
  37.         self.lasted = []
  38.         self.prompt = "总共运行了"
  39.         for index in range(6):
  40.             temp = self.end[index] - self.begin[index]

  41.             # 低位不够减,需向高位借位
  42.             if temp < 0:
  43.                 # 测试高位是否有得“借”,没得借的话向再高位借......
  44.                 i = 1
  45.                 while self.lasted[index-i] < 1:
  46.                     self.lasted[index-i] += self.borrow[index-i] - 1
  47.                     self.lasted[index-i-1] -= 1
  48.                     i += 1

  49.                 self.lasted.append(self.borrow[index] + temp)
  50.                 self.lasted[index-1] -= 1
  51.             else:
  52.                 self.lasted.append(temp)

  53.         # 由于高位随时会被借位,所以打印要放在最后
  54.         for index in range(6):
  55.             if self.lasted[index]:
  56.                 self.prompt += str(self.lasted[index]) + self.unit[index]

  57.         # 为下一轮计时初始化变量
  58.         self.begin = 0
  59.         self.end = 0
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-20 20:03

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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