一个没有暂停和复位功能的计时器

独自空忆成欢 提交于 2020-02-05 10:02:46
import time
import datetime


class Timer:
    def __init__(self):
        self.prompt = '未开始计时'
        self.start_time = 0
        self.stop_time = 0
        self.time_subtraction = 0

    def __str__(self):
        return self.prompt

    __repr__ = __str__

    def __add__(self, other):
        prompt = "共运行了"
        result = self.time_subtraction + other.time_subtraction
        return prompt + str(result)

    def start_clock(self):
        self.start_time = time.clock()
        print('定时器已启动')

    def stop_clock(self):
        self.stop_time = time.clock()
        self._cacle()
        print('计时器已停止')
        if not self.start_time:
            return print('定时器还没开启呢')
        return print(self.prompt)

    def _cacle(self):
        self.time_subtraction = datetime.timedelta(seconds=(self.stop_time-self.start_time))
        self.prompt = '计时结果为:'+str(self.time_subtraction)


if __name__ == '__main__':
    t1 = Timer()
    print(t1)
    t1.start_clock()
    time.sleep(2)
    t1.stop_clock()


    t2 = Timer()
    t2.start_clock()
    time.sleep(3)
    t2.stop_clock()

    print(t1+t2)

输出结果:

未开始计时
定时器已启动
计时器已停止
计时结果为:0:00:02.000031
定时器已启动
计时器已停止
计时结果为:0:00:03.000170
共运行了0:00:05.000201

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!