|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#小甲鱼44课计时器 课堂源代码,我将add(self)方法中的prompt变量修改为prompt_t,但是执行t1+t2时,仍然正常有描述的语句’‘总共运行了13秒' ’,不知道
__repr__(self)是如何接收到add(self)方法中的返回值的呢?__repr__(self)的返回值self.prompt和add()方法的返回值 return promptp_t,变量不一样,而且add()方法
不带self,求详解
- import time as t
- class MyTimer():
- def __init__(self):
- self.unit = ['年','月','天','小时','分','秒']
- self.lasted = []
- self.prompt = '未开始计时'
- self.begin = 0
- self.end = 0
- def __repr__(self):
- return self.prompt
-
- __str__ = __repr__
- #加法
- def __add__(self,other):
- prompt_t='总共运行了'
- result =[]
- for index in range(6):
- result.append(self.lasted[index]+other.lasted[index])
- if result[index]:
- promptp_t+=(str(result[index]) + self.unit[index])
- return promptp_t #原变量为prompt
-
- #开始计时
- def start(self):
- self.begin = t.localtime()
- self.prompt = '提示,请先调用stop方法,结束计时'
- print('计时开始')
- #计时结束
- def stop(self):
- if self.begin:
- self.end = t.localtime()
- self._calc()
- print('计时结束')
- else:
- print('提示,请先调用start方法,开始计时')
- #内部方法,计算运行时间
- 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
复制代码
'''
>>> t2 =MyTimer()
>>> t1=MyTimer()
>>> t2.start()
计时开始
>>> t2.stop()
计时结束
>>> t1.start()
计时开始
>>> t1.stop()
计时结束
>>> t1
总共运行了5秒
>>> t2
总共运行了8秒
>>> t1 +t2
'总共运行了13秒'
''' |
|