天天看點

python計時器程式_python簡單計時器實作

實作程式運作時間的顯示與互相之間的計算:

實作代碼:

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]

實作結果如下:

python計時器程式_python簡單計時器實作