python实现计时器

 1 import time
 2 
 3 class MyTimer():
 4     def __init__(self):
 5         self.prompt="未开始计时!"
 6         self.unit=["","","","","",""]
 7         self.begin=0
 8         self.end=0
 9         self.l=[]
10 
11     def __add__(self,other):
12         result=[]
13         prompt="共计:"
14         for i in range(6):
15             result.append(self.l[i]+other.l[i])
16             if result[i]:
17                 prompt+=(str(result[i])+self.unit[i])
18         return prompt
19 
20     def start(self):
21         self.prompt="请先调用stop()函数"
22         print("开始计时...")        
23         self.begin=time.localtime()
24 
25     def stop(self):
26         if not self.begin:
27             print("请先调用start()函数")
28             return
29         print("停止计时!")
30         self.end=time.localtime()
31         self.prompt="共运行:"
32         self.l=[]#在进行计算前先清空历史记录
33         for i in range(6):
34             self.l.append(self.end[i]-self.begin[i])
35             if self.l[i]:
36                 self.prompt+=(str(self.l[i])+self.unit[i])
37         self.begin=0
38         self.end=0        
39 
40     def __str__(self):        
41         #print(对象)即调用对象的__str__函数,此函数要返回一个String对象,即返回一个字符串,类似java中打印一个对象即调用这个对象的tostring方法。
42         return self.prompt
43 
44     #此函数或直接写成__repr__=__str__
45     def __repr__(self):
46         #直接运行对象即调用对象__repr__函数,并打印此函数的返回值,此函数的返回值为字符串类型
47         return self.prompt

 

posted @ 2017-11-07 16:09  xiongjiawei  阅读(1974)  评论(0)    收藏  举报