|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 694061755 于 2017-11-12 10:39 编辑
import time as t
class MyTimer:
def __init__(self):
self.unit = ['年','月','天','小时','分钟','秒']
self.prompt = "计时未开始!"
self.lasted = []
self.begin = 0
self.end = 0
def __str__(self):
return self.prompt
__repr__ = __str__
#开始计时
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]) 请问:这一句里的str(self.lasted[index])和self.unit[index]两个列表只是相加就 变成或者说合并成一个 年月天小时分钟秒 的格式了,为什么?能说下原理吗?谢谢大家!!!
def _calc(self):
self.lasted = []
self.prompt = "总共运行了"
for index in range(6): #因为unit中有6项,'年','月','天','小时','分钟','秒',这里进行循环赋值
self.lasted.append(self.end[index] - self.begin[index]) #计算每一项的时间差
if self.lasted[index]:
self.prompt += (str(self.lasted[index]) + self.unit[index]) #将每一项的时间差和后面的单位,也就'年','月','天','小时','分钟','秒'进行拼接
大致的过程上面的注释给你说了一遍,这里是通过分别对每一项,也就是'年','月','天','小时','分钟','秒'分别进行拼接,实现最后的格式
|
|