python计时器单位,python(计时器)
計(jì)時器
要求:
定制一個計(jì)時器的類
start 和 stop方法代表啟動計(jì)時和停止計(jì)時
假設(shè)計(jì)時器對象 t1,print(t1)和直接調(diào)用t1 均顯示結(jié)果
當(dāng)計(jì)時器未啟動或已停止計(jì)時,調(diào)用stop方法能給予溫馨提示
兩個計(jì)時器對象可以相加: t1 + t2
只能使用提供的有限資源完成
資源:
使用time模塊的localtime方法獲取時間
time.localtime返回 struct_time的時間格式
表現(xiàn)你的類: _ str _ 和 _ repr _(str調(diào)用時要用print,repr可直接調(diào)用)
import time as t
class MyTimer:
#開始計(jì)時
def start(self):
self.begin = t.localtime()
self.prompt = '提示:請先用stop()停止計(jì)時'
print('開始計(jì)時')
#停止計(jì)時
def stop(self):
if not self.begin:
print('提示:請先用start()開始計(jì)時')
else:
self.end = t.localtime()
self._calc()
print('計(jì)時結(jié)束')
#計(jì)時器相加
def __add__(self,other):
prompt = '總共運(yùn)行了'
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 = '未開始計(jì)時'
self.lasted = []
self.begin = 0
self.end = 0
def __str__(self):
return prompt#重寫__str__魔法方法,程序在調(diào)用print函數(shù)時,打印當(dāng)時狀態(tài)的prompt內(nèi)容
__repr__ = __str__#將__repr__和__str__相同化
#內(nèi)部方法,計(jì)算運(yùn)行時間
def _calc(self):
self.lasted = []#制作一個空列表,存放每個單位相減的值
self.prompt = '總共運(yùn)行了'
for index in range(6):
temp = self.end[index] - self.begin[index]
if temp < 0:
i = 1
while self.lasted[index -i] < 1:#向前邊的位數(shù)借
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]
#為下一輪計(jì)時初始化變量
self.begin = 0
self.end = 0
運(yùn)行結(jié)果:
>>>t1 = MyTimer()
>>>t1
>>>未開始計(jì)時
>>>t1.statrt()
>>>開始計(jì)時
>>>t1.stop()
>>>計(jì)時結(jié)束
>>>t1
>>>總共運(yùn)行了5秒
>>>t2=MyTimer()
>>>t2.stop()
>>>提示:請先用start()開始計(jì)時
>>>t2.start()
>>>開始計(jì)時
>>>t2
>>>提示:請先用stop()停止計(jì)時
>>>t2.stop()
>>>計(jì)時結(jié)束
>>>t2
>>>總共運(yùn)行了5秒
>>>t1 + t2
>>>總共運(yùn)行了10秒
總結(jié)
以上是生活随笔為你收集整理的python计时器单位,python(计时器)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 国六排放实施对汽车的影响
- 下一篇: python virtualenv ng