|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
代码如下,
import time as t
print(t.localtime()) #输出格式如下行
#time.struct_time(tm_year=2019, tm_mon=1, tm_mday=30, tm_hour=21, tm_min=9, tm_sec=15, tm_wday=2, tm_yday=30, tm_isdst=0)
class MyTimer:
def __init__(self): #防呆设计,使在初始时即创建了全部的属性,防止报错
self.prompt='未开始计时!'
self.lasted=[]
self.begin=0
self.end=0
self.unit=['年','月','日','小时','分钟','秒'] #为了使得最后反馈的小时更人性化,故加入此属性
#开始计时
def start(self):
self.begin=t.localtime()
print('开始计时...')
self.prompt='提示:请先调用stop()结束计时'#加入防呆提示
#停止计时
def stop(self):
if not self.begin:#加入防呆提示
print('提示:请先调用start()开始计时')
else:
self.end=t.localtime()
self._calc() #调用下面的计时函数
print('计时结束...')
def _calc(self):
self.lasted=[]
self.prompt='总共运行了' #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])
if self.prompt=="总共运行了":
self.prompt+='0秒'
print(self.prompt)
def __str__(self):#本函数在于重写str,使得print(t1)和直接调用t1均显示结果
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 __sub__(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
t1=MyTimer()
t2=MyTimer()
__add__是小甲鱼老师定义的,我自己定义了一个__sub__减法运算却报错,请教鱼油问题出在哪儿?谢谢!
prompt+=(str(result[index]+self.unit[index])
str函数少打一个括号
|
|