第44讲,计时器的问题,为什么直接把localtime()替换为perf_counter()不可以呢
报错内容:Traceback (most recent call last):
File "<pyshell#125>", line 1, in <module>
t.stop()
File "D:/untitled/44_.py", line 40, in stop
self.__calc()
File "D:/untitled/44_.py", line 47, in __calc
self.lasted.append(abs(self.end - self.begin))
TypeError: 'float' object is not subscriptable
我的代码(其实就是鱼老师上课讲的,我只是做了时间模块函数的替换)
#计时器
import time
class Mytimer:
def __init__(self):
self.unit = ['年','月','日','时','分','秒']
self.prompt = "未开始计时"
self.begin = 0
self.end = 0
self.lasted = []
def __str__(self):
return self.prompt
__repr__ = __str__
def __add__(self,other):
prompt = "总共运行了:"
result = []
for index in range(6):
result.append(self.lasted + other.lasted)
if result:
prompt+=(str(result)+self.unit)
return prompt
def start(self):
self.begin = time.perf_counter()
self.prompt = "提示:请先调用stop()停止计时"
print("计时开始")
def stop(self):
if not self.begin:
print("提示:请先调用start()开始计时")
else:
self.end = time.perf_counter()
self.__calc()
print("计时停止")
def __calc(self):
self.lasted = []
self.prompt = "总共运行了:"
for index in range(6):
self.lasted.append(abs(self.end - self.begin))
if self.lasted:
self.prompt += (str(self.lasted+self.begin))
self.begin = 0
self.end = 0
localtime()的结果是一个元组,perf_counter()的结果是一个浮点数,不能直接替换。
页:
[1]