|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Peteryo01223 于 2021-3-17 11:14 编辑
第44课,视频中举例如下:
- import time as t
- class MyTimer():
- # 开始计时
- def start(self):
- self.start = t.localtime()
- print('计时开始。。。')
- # 停止计时
- def stop(self):
- self.stop = t.localtime()
- self._calc() # 这里调用了计算方法,为何在上面 start中不用计算呢?
- print('计时结束。')
- # 内部方法,计算运行时间
- def _calc(self):
- self.lasted = []
- self.prompt = '总共运行了'
- for index in range(6): # 这句何意?range(6),是1、2、3、4、5的意思吧?index 有定义过是什么吗?
- self.lasted.append(self.stop[index] - self.start[index])
- self.prompt += str(self.lasted[index])
- print(self.prompt)
-
复制代码
提问:
1. 第12行code,为何定义stop时用了self._calc(),而定义start时,不用呢?
2. 第19行code,为何用数字 6 ,不用其它数值?index没有定义过吧?range(6),是1、2、3、4、5的意思,5次 for 循环在干嘛?
谢谢~
本帖最后由 jackz007 于 2021-3-17 15:00 编辑
答案就在 time . localtime() 返回的东西上,让我们看看返回了些什么
- >>> import time
- >>> print(time . localtime()[:6])
- (2021, 3, 17, 13, 37, 37)
- >>>
复制代码
就是说,MyTimer 类中的属性 start 和 stop 是可迭代对象,通过循环切片,可以从中依次得到年、月、日、时、分、秒的数值。我想,不用再做进一步的解释了吧?
可以把原代码改造一下,让它功能基本相同,却要简单和好理解一些,尤其是 _calc() 方法。
- import time
- class MyTimer():
- # 开始计时
- def start(self):
- self . start = int(time . time()) # 自格林威治时间 1970年1月1日0时0分0秒起至今经历的时钟秒数
- print('计时开始。。。')
- print(time . localtime()[: 6])
- # 停止计时
- def stop(self):
- self . stop = int(time . time()) # 自格林威治时间 1970年1月1日0时0分0秒起至今经历的时钟秒数
- print('计时结束。')
- print(time . localtime()[: 6])
- # 内部方法,计算运行时间
- def _calc(self):
- print(self . stop - self . start)
- s = MyTimer()
- s . start()
- for _ in range(888888888):
- pass
- s . stop()
- s . _calc()
复制代码
运行实况
- D:\0002.Exercise\Python>python tx.py
- 计时开始。。。
- (2021, 3, 17, 14, 35, 22)
- 计时结束。
- (2021, 3, 17, 14, 36, 26)
- 64
- D:\0002.Exercise\Python>
复制代码
64 代表 start 和 stop 之间的时间间隔是 64 秒。
|
|