實作程式運作時間的顯示與互相之間的計算:
實作代碼:
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 __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]
實作結果如下:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnL3ADNwcDN1QDMy0SMwQjNwgzMwAjMxITM4EDMy0CMxQTO5QTMvwlMxgTMwIzLcBTM0kTO0EzLcd2bsJ2Lc12bj5ycn9Gbi52YugTMwIzZtl2Lc9CX6MHc0RHaiojIsJye.png)