本帖最后由 2012277033 于 2021-8-10 12:21 编辑
你这个代码问题太多了,大致猜测你应该将time重命名为t了,按照你的思路,大概改了下:import time as t
class Mytimer:
def __init__(self):
self.t1 = []
self.t2 = []
self.t3 = []
self.t4 = []
def start(self):
self.t1.append(t.strftime("%H",t.localtime()))
self.t1.append(t.strftime("%M",t.localtime()))
self.t1.append(t.strftime("%S",t.localtime()))
print('开始计时……')
def stop(self):
self.t2.append(t.strftime("%H",t.localtime()))
self.t2.append(t.strftime("%M",t.localtime()))
self.t2.append(t.strftime("%S",t.localtime()))
self._calc()
def _calc(self):
if self.t1 == []:
print("请先调用start函数")
return
else:
#这里这么计算,是当比如说11:53:57 到11:54:02的时候,产生负数,就要借一
self.t3.append(int(self.t2[2]) - int(self.t1[2]))
if self.t3[0]<0:
self.t3[0]+=60
self.t2[1]=str(int(self.t2[1])-1)
self.t3.insert(0,int(self.t2[1]) - int(self.t1[1]))
if self.t3[0]<0:
self.t3[0]+=60
self.t2[0]=str(int(self.t2[0])-1)
self.t3.insert(0,int(self.t2[0]) - int(self.t1[0]))
print("停止计时")
print("总共运行了{}时{}分{}秒".format(self.t3[0],self.t3[1],self.t3[2]))
def __add__(self,other):
self.t4.append(self.t3[0]+other.t3[0])
self.t4.append(self.t3[1]+other.t3[1])
if self.t4[1]>=60:
self.t4[1]=60-self.t4[1]
self.t4[0]+1
self.t4.append(self.t3[2]+other.t3[2])
if self.t4[2]>=60:
self.t4[2]=60-self.t4[2]
self.t4[1]+1
if self.t4[1]>=60:
self.t4[1]=60-self.t4[1]
self.t4[0]+1
print("总共运行了{}时{}分{}秒".format(self.t4[0],self.t4[1],self.t4[2]))
self.t1 = []
self.t2 = []
self.t3 = []
t3 = Mytimer()
t2 = Mytimer()
t3.start()
t.sleep(2)
t3.stop()
t2.start()
t.sleep(2)
t2.stop()
t2+t3
不过,其实实现计时器可以更简单点:import time as time
class Mytimer:
def __init__(self):
self.starttime=0
self.count=0
def start(self):
self.starttime=int(time.time())
print('开始计时……')
def stop(self):
self.count=int(time.time())-self.starttime
print("共运行了{}时{}分{}秒".format(self.count//3600,self.count//60%60,self.count%60))
def __add__(self,other):
temp = self.count+other.count
print("共运行了{}时{}分{}秒".format(temp//3600,temp//60%60,temp%60))
self.starttime=0
self.count=0
t3 = Mytimer()
t2 = Mytimer()
t3.start()
time.sleep(2)
t3.stop()
t2.start()
time.sleep(2)
t2.stop()
t2+t3
|