Python面向对象编程之实战——MyTimer制作
制作一个计时器,用来计算程序运行时间!
以下是实现代码:
import time as t
class MyTimer:
def __init__(self):
self.prompt="未开始计时"
self.unit=["年","月","日","时","分钟","秒"]
self.lasted=[]
self.begin=0
self.end=0
def __str__(self):
return self.prompt
__repr__=__str__
#计算两次运行结果的和
def __add__(self,other):
result=[]
Timer="一共运行了"
for index in range(6):
result.append(self.lasted[index]+other.lasted[index])
Timer+=str(result[index])+self.unit[index]
return Timer
#开始计时
def start(self):
self.begin=t.localtime()
self.prompt="请先结束程序在查看运行时间!"
print("计时开始!")
#停止计时
def stop(self):
if not self.begin:
print("请先开始计时!")
else:
self.end=t.localtime()
print("计时结束!")
self._calc()
#内部方法,计算时间
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