Python计时器小程序
import time as tm
class MyTimer():
'''我的计时器bykc20170702'''
def __init__(self):
self.begin = False
self.end = False
self.time = {"start":[],"end":[],"cost":[]}
self.info = "init"
self.unit = ["年","月","日","时","分","秒"]
def __str__(self):
if not self.begin:
return "未开始计时呢"
elif not self.end:
return "需要停止计时"
return self.info # 打印计时时间
__repr__ = __str__
def reset(self):
'''重置'''
pass
def start(self):
'''开始计时'''
if self.begin:
print("计时器计时中,请stop()停止后操作")
return None
self.begin = True
self.time["start"] = tm.localtime()
print("开始计时...")
def stop(self):
'''停止计时'''
if not self.begin:
print("计时器未计时,请先start()开始后操作")
return None
self.end = True
self.time["end"] = tm.localtime()
self._calc()
print("结束计时...")
def _calc(self):
'''内部计算方法'''
for index in range(6):
tmp = self.time["end"][index]-self.time["start"][index];
self.time["cost"].append(tmp)
self.info = "计时器运行了:"
if tmp:
self.info += (str(tmp) + self.unit[index])
# 重置
self.begin = False
self.end = False