計時器
要求:
定制一個計時器的類
start 和 stop方法代表啟動計時和停止計時
假設計時器對象 t1,print(t1)和直接調用t1 均顯示結果
當計時器未啟動或已停止計時,調用stop方法能給予溫馨提示
兩個計時器對象可以相加: t1 + t2
只能使用提供的有限資源完成
資源:
使用time模塊的localtime方法獲取時間
time.localtime返回 struct_time的時間格式
表現你的類: _ str _ 和 _ repr _(str調用時要用print,repr可直接調用)
import time as t
class MyTimer:
#開始計時
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 __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 __init__(self):
self.unit = ['年','月','天','小時','分鐘','秒']
self.borrow= [0,12,31,24,60,60]
self.prompt = '未開始計時'
self.lasted = []
self.begin = 0
self.end = 0
def __str__(self):
return prompt#重寫__str__魔法方法,程序在調用print函數時,打印當時狀態的prompt內容
__repr__ = __str__#將__repr__和__str__相同化
#內部方法,計算運行時間
def _calc(self):
self.lasted = []#制作一個空列表,存放每個單位相減的值
self.prompt = '總共運行了'
for index in range(6):
temp = self.end[index] - self.begin[index]
if temp < 0:
i = 1
while self.lasted[index -i] < 1:#向前邊的位數借
self.lasted[index - i] += self.borrow[index - i] - 1
self.lasted[index - i - 1] -= 1
i += 1#向更高位借
self.lasted.append(self.borrow[index] + temp)
self.lasted[index - 1] -= 1
else:
self.lasted.append(temp)
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
運行結果:
>>>t1 = MyTimer()
>>>t1
>>>未開始計時
>>>t1.statrt()
>>>開始計時
>>>t1.stop()
>>>計時結束
>>>t1
>>>總共運行了5秒
>>>t2=MyTimer()
>>>t2.stop()
>>>提示:請先用start()開始計時
>>>t2.start()
>>>開始計時
>>>t2
>>>提示:請先用stop()停止計時
>>>t2.stop()
>>>計時結束
>>>t2
>>>總共運行了5秒
>>>t1 + t2
>>>總共運行了10秒