1. import time as t
    2. class MyTimer():
    3. def __init__(self):
    4. self.unit = ["年", "月", "天", "时", "分钟", "秒"]
    5. self.prompt = "未开始计时"
    6. self.lasted = []
    7. self.begin = 0
    8. self.end = 0
    9. # 重写
    10. def __str__(self):
    11. return self.prompt
    12. __repr__ = __str__
    13. def __add__(self, other):
    14. prompt = "总共运行了"
    15. result =[]
    16. for index in range(6):
    17. result.append(self.lasted[index] + self.other.lasted[index])
    18. if result[index]:
    19. prompt += (str(result[index]) +self.unit[index])
    20. return prompt
    21. # 开始计时
    22. def start(self):
    23. self.begin = t.localtime()
    24. self.prompt ="提示: 请先调用stop() 停止计时"
    25. print("开始计时...")
    26. # 停止计时
    27. def stop(self):
    28. if not self.begin:
    29. print("提示: 请先调用start() 运行计时")
    30. else:
    31. self.end = t.localtime()
    32. self._calc()
    33. print ("停止计时")
    34. # 内部方法 计算运行时间 )前面使用下划线来区分
    35. def _calc(self):
    36. self.lasted = []
    37. self.prompt = "总共运行了"
    38. for index in range(6):
    39. self.lasted.append(self.end[index] - self.begin[index])
    40. if self.lasted[index]:
    41. self.prompt += (str(self.lasted[index]) + self.unit[index])