定制一个计时器,实现以下要求
1、定制一个计时器的类
2、start和stop方法代表启动计时和停止计时
3、假设计时器对象t1,print(t1)和直接调用t1均显示结果
4、当计时器未启动或已经停止计时,调用stop方法会给予相应的提示
5、两个计时器对象可以相加
由上可见,重写repr值就可以时类的对象输出想要的
普通版计时器
import time as t
class MyTimer:
#初始化,防止一开始还没有调用start就让他输出对象的值,此时prompt还没有被定义会出错
def __init__(self):
self.prompt="未开始计时"
self.unit=['年','月','日','时','分','秒']
self.lasted=[]
self.begin=0
self.end=0
def __str__(self):
return self.prompt
__repr__=__str__
def __add__(self,other):
prompt="总共运行了"
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("计时开始!")
#停止计时
def stop(self):
if not self.begin:
print("提示:请先用start()进行计时")
else:
self.end=t.localtime()
self._calc()
print("计时结束!")
#计算时间
def _calc(self):
self.lasted=[] #用来存放运算结果
self.prompt="总共运行了"
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])
print(self.prompt)