计时器题目
import time as tclass MyTimer:
def __init__(self):
self.begin = 0
self.end = 0
self.list = []
self.unit = ["年","月","日","时","分","秒"]
def start(self):
self.begin = t.localtime()
return type(self.begin)
def stop(self):
self._calc()
self.end = t.localtime()
## def _calc(self):
##
## for i in range(6):
## self.list.append(self.end-self.begin)
## for j in range(0,6):
## print(str(self.list)+unit)
def _calc(self):
self.lasted = []
self.prompt = "总共运行了"
for index in range(6):
self.lasted.append(self.end - self.begin)
if self.lasted:
self.prompt += (str(self.lasted) + self.unit)
# 为下一轮计时初始化变量
self.begin = 0
self.end = 0
m = MyTimer()
line 28, in _calc
self.lasted.append(self.end - self.begin)
TypeError: 'int' object is not subscriptable
为什么这里报成int呀,小甲鱼代码里calc也是这么写的呀,求助大佬们.这个就是计时器那个题目 本帖最后由 阿奇_o 于 2021-5-21 17:47 编辑
首先因为,你初始化时self.begin=0, self.end=0,0就是int整型!整型肯定不能用[] 。
其次,用 localtime 是不是太那个了。。
假设self.begin 刚好是 ..59秒,两秒后 stop() 那 self.end的秒数,就是 01秒,
这个时候,秒数相减,即 self.end - self.begin 你如何得到正确的秒数差?考虑进制的情况?分时天月年 都考虑?……
所以,我个人是不建议用 time.localtime() 来做计时的,我选择用time.time(),不仅精确、易懂,对秒分时的进制处理也更方便。
from time import time, sleep, localtime
# 用time.time()精确计时
class MyTimer():
def start(self):
self.begin = time()
print("计时器已启动,正在计时……")
def stop(self):
self.end = time()
print("计时器已停止。")
lasted = self._cal()
return lasted
def _cal(self):
seconds = self.end - self.begin # 精确运行秒数(浮点数)
mins, sec = divmod(seconds, 60) # 满60秒,即进1分钟
hours, min = divmod(mins, 60)# 满60分钟,即进1小时(最大以小时来衡量)
return f"计时共计:{int(hours)}小时 {int(min)}分钟 {sec}秒"
mt = MyTimer()
mt.start()
sleep(2)
print(mt.stop())
begin和end不都是整型数值,你给他安个中括号是为哪端
页:
[1]