python——初级定时器

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'
>>> 

有时候会出现负数,以后再改吧……
全部评论

相关推荐

12-18 22:04
已编辑
杭州电子科技大学 Java
程序员牛肉:我觉得是这样的,你现在有点病急乱投医了。你要问自己这样一个问题: 我找实习的目的是什么?为了挣钱还是增强个人实力?如果是为了挣钱那没得说,如果我是为了增强个人实习,那我异地去一个小厂实习真的有收益吗?这个收益是否大过我参加学校的项目或者自学?我记得你们杭电有那种实验室专门负责运维学校的项目的。 找实习只是一个手段而已,不要把他变成目的。不要病急乱投医。
实习简历求拷打
点赞 评论 收藏
分享
头像
11-06 19:52
已编辑
携程_移动安全研发
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务