|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 luoyuzimo 于 2019-4-26 16:38 编辑
import time as t
class MyTimer:
#初始化类变量
def __init__(self):
self.unit = ['年','月','天','小时','分钟','秒']
self.prompt = '尚未开始计时!'
self.begin = 0
self.end = 0
self.lasted = []
#实现打印一个类对象时的魔法方法
def __str__(self):
return self.prompt
#实现输出一个类对象时的魔法方法
__repr__ = __str__
def __add__(self, other):
self.prompt = '总共运行了:'
result = []
for i in range(6):
result.append(self.lasted[i] + other.lasted[i])
if result[i]:
self.prompt += str(result[i]) + self.unit[i]
return self.prompt -- add中的prompt加了个self,导致调用t1 + t2,再打印t1时结果和t1+t2一样,但是打印t2的结果又不一样,是为什么?
#开始计时
def start(self):
self.begin = t.localtime()
print("开始计时")
#结束计时
def stop(self):
self.end = t.localtime()
self._calc()
print("计时结束")
#计算从开始到结束花了多长时间
def _calc(self):
self.prompt = '总共运行了:'
self.lasted = []
for i in range(6):
self.lasted.append(self.end[i] - self.begin[i])
if self.lasted:
self.prompt += str(self.lasted[i]) + self.unit[i]
下面是运行结果:
>>>t1 = MyTimer()
>>>t1.start()
开始计时
>>>t1.stop()
计时结束
>>>t1
总共运行了:0年0月0天0小时0分钟6秒
>>>t2 = MyTimer()
>>>t2.start()
开始计时
>>>t2.stop()
计时结束
>>>t2
总共运行了:0年0月0天0小时0分钟7秒
>>>t1 + t2
'总共运行了:13秒'
>>>t1
总共运行了:13秒 ---为什么t1是显示的t1+t2的结果??
>>>t2
总共运行了:0年0月0天0小时0分钟7秒 ---t2为什么又是显示的是自身的结果??
|
|