代码:
import time as t
class MyTimer():
def __init__(self):
self.unit = ['年','月','天','小时','分钟','秒']
self.prompt = "未开始"
self.lasted = []
self.start = 0
self.stop = 0
def __str__(self):
return self.prompt
def __add__(self , other):
prompt = "总共运行了:"
result = []
for i in range(6):
result.append(self.lasted[i] + other.lasted[i])
if result[i]:
prompt +=(str(result[i]) + self.unit[i])
return prompt
__repr__=__str__
#开始计时
def begin (self):
self.start = t.localtime()
self.prompt = "请先停止在进行计时"
print ("计时开始")
#停止计时
def end (self):
if not self.start:
print("请先开始再进行计时")
else:
self.stop = t.localtime()
self._calc()
print ("计时结束")
#内部方法,计算运行时间
def _calc(self):
self.lasted = []
self.prompt = "总共运行了"
for i in range(6):
self.lasted.append(self.stop[i] - self.start[i])
if self.lasted[i] :
self.prompt +=(str(self.lasted[i]) + self.unit[i])
self.stop = 0
self.start = 0
运行结果:
>>> t1 = MyTimer()
>>> t1.begin()
计时开始
>>> t1.end()
计时结束
>>> t1
总共运行了4秒
>>> t2 = MyTimer()
>>> t2.begin()
计时开始
>>> t2.end()
计时结束
>>> t2
总共运行了5秒
>>> t1 + t2
'总共运行了:9秒'