计时器

 1 import time as t
 2 
 3 class MyTimer():
 4     def __init__(self):
 5         self.unit = ['','','','小时','分钟','']
 6         self.prompt = '未开始计时'
 7         self.lasted = []
 8         self.begin = 0
 9         self.end = 0
10     def __str__(self):
11         return self.prompt
12     __repr__ = __str__
13     def __add__(self, other):
14         prompt = '总共运行了'
15         result = []
16         for index in range(6):
17             result.append(self.lasted[index] + other.lasted[index])
18             if result[index]:
19                 prompt += (str(result[index]) + self.unit[index])
20         return prompt
21     #开始计时
22     def start(self):
23         self.begin = t.localtime()
24         self.prompt = '提示:请先调用stop()停止计时'
25         print('计时开始。。。')
26     #停止计时
27     def stop(self):
28         if not self.begin:
29             print('提示:请先调用start()进行计时')
30         else:
31             self.end = t.localtime()
32             self._calc()
33             print('计时结束!')
34 
35     #内部方法,计算运行时间
36     def _calc(self):
37         self.lasted = []
38         self.prompt = '总共运行了'
39         for index in range(6):
40             self.lasted.append(self.end[index] - self.begin[index])
41             if self.lasted[index]:
42                 self.prompt += str(self.lasted[index]) + self.unit[index]
43         #为下一轮计时初始化变量
44         self.begin = 0
45         self.end = 0
46         #print(self.prompt)
原文地址:https://www.cnblogs.com/vigossr/p/10234327.html