美文网首页
Python 计时器 小甲鱼随堂练习

Python 计时器 小甲鱼随堂练习

作者: 大师的学徒 | 来源:发表于2020-03-05 00:27 被阅读0次
import time as t

class MyTimer():

    def __init__(self):
        self.prompt = 'Timer Not Running! '
        self.unit = ['Year','Month','Day','Hrs','Min','s']
        self.begin = 0
        self.end = 0

    def __str__(self):
        return self.prompt

    __repr__ = __str__

    def __add__(self, other):
        prompt = 'Total running time is '
        result = []
        for i in range(6):
            result.append(self.last[i] + other.last[i])
            if result[i]:
                prompt += (str(result[i]) + self.unit[i])
        return prompt
    
    #start timing
    def start(self):
        self.begin = t.localtime()
        self.prompt = 'Please STOP first!'
        print('START TIMING')

    #stop timing
    def stop(self):
        if not self.begin:
            print('Please START first!')
        else:
            self.end = t.localtime()
            self._calc()
            print("STOP!")

    #bound method calculate
    def _calc(self):
        self.last = []
        self.prompt = 'Running Time is '
        for i in range(6):
            self.last.append(self.end[i] - self.begin[i])
            if self.last[i]:
                self.prompt += (str(self.last[i]) + self.unit[i])

        # back to 0
        self.begin = 0
        self.end = 0

相关文章

网友评论

      本文标题:Python 计时器 小甲鱼随堂练习

      本文链接:https://www.haomeiwen.com/subject/riwglhtx.html