您的位置:首页 > 编程语言 > Python开发

python——初级定时器

2016-07-29 11:45 232 查看
import time as t
class MyTimer():
def __init__(self):
self.unit=['year','month','day','hour','minute','sec']
self.prompt='未开始';
self.lasted=[]
self.begin=0
self.end=0
def __str__(self):
return self.prompt
__repr__=__str__
def __add__(self,other):
prompt="totle time:"
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
#start
def start(self):
self.begin=t.localtime()
self.prompt='please stop';
print('start')
#end
def stop(self):
if not self.begin:
print('please start')
else:
self.end=t.localtime()
self._calc()
print('end')
#inner function calulate runtime
def _calc(self):
self.lasted=[]
self.prompt='runtime:'
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])
print(self.prompt)
self.begin=0
self.end=0
>>> t1=MyTimer()
>>> t1.start()
start
>>> t2.stop()
Traceback (most recent call last):
File "<pyshell#63>", line 1, in <module>
t2.stop()
NameError: name 't2' is not defined
>>> t1.stop()
runtime:10sec
end
>>> t2=MyTimer()
>>> t2.start()
start
>>> t2.stop()
runtime:4sec
end
>>> t1+t2
'totle time:14sec'
>>>


有时候会出现负数,以后再改吧……
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: