定制一个计时器
目录
定制一个计时器的类
start方法和stop方法代表启动和停止计时器
计时器对象t1和print(t1)均均显示结果
当计时器未启动或已经停止时,调用stop会给予温馨提示
两个计时器对象可以进行相加t1+t2
只能使用提供的有限资源完成
import time as t
class MyTimer():
def __init__(self):
self.unit = ["年","月","日","时","分","秒"]
self.prompt = "no starting"
self.lasted = []
self.begin = 0
self.end = 0
def __str__(self):
return self.prompt
__repr__=__str__
def __add__(self,other):
prompt = "total runing"
result = []
for index in range(6):
result.append(self.lasted[index]+other.lasted[index])
if result[index]:
prompt += (str(result[index]) + self.unit[index])
return prompt
#开始计时
def start(self):
self.begin = t.localtime()
self.prompt = "提示:请先调用stop()停止计时!"
print("time starting...")
#停止计时
def stop(self):
if not self.begin:
print("提示:请先调用start()停止计时!")
else:
self.end = t.localtime()
self._calc()
print("time ending...")
#内部方法计算运行时间
def _calc(self):
self.lasted = []
self.prompt = "total runing:"
for index in range(6):
self.lasted.append(self.end[index]- self.begin[index])
if self.lasted[index]:
self.prompt += str(self.lasted[index])+self.unit[index]
#为下一轮计时初始化变量
self.begin = 0
self.end = 0
运行结果展示: