Python入門學習筆記( 魔法方法 簡單定製)

https://fishc.com.cn/forum.php?mod=viewthread&tid=51326&extra=page%3D1%26filter%3Dtypeid%26typeid%3D403

import time as t

class Mytimer():
    def __init__(self):
        self.unit = ['年','月','天','小時','分鐘','秒']
        self.prompt = "未開始計時!"
        self.lasted = []
        self.begin = 0
        self.end = 0

    def __str__(self):
        return self.prompt

    __repr__=__str__


    def __add__(self,other):
        prompt = "總共運行了"
        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
                
    #開始計時
    def start(self):
        self.begin = t.localtime()
        self.prompt = "提示:請先調用 stop() 停止計時!"
        print("計時開始...")

    #停止計時
    def stop(self):
        if not self.begin:
            print("提示:請先調用start()進行計時!")
        else:
            self.end = t.localtime()
            self._calc()
            print("計時結束!")

    #內部方法計算運行時間
    def _calc(self):
        self.lasted = []
        self.prompt = "總共運行了"
        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])
        #爲下一輪計時初始化變量
        self.begin = 0
        self.end = 0

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章