日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python计时器单位,python(计时器)

發布時間:2025/3/8 python 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python计时器单位,python(计时器) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

計時器

要求:

定制一個計時器的類

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秒

總結

以上是生活随笔為你收集整理的python计时器单位,python(计时器)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。