Python基础入门学习笔记 044 魔法方法:简单定制


简单定制

?基本要求:

–定制一个计时器的类

–start和stop方法代表启动计时和停止计时

–假设计时器对象t1,print(t1)和直接调用t1均显示结果

–当计时器未启动或已经停止计时,调用stop方法会给予温馨的提示

–两个计时器对象可以进行相加:t1 + t2

–只能使用提供的有限资源完成

你需要这些资源

?使用time模块的localtime方法获取时间

?time.localtime返回struct_time的时间格式

?表现你的类:__str__ 和 __repr__

1 import time as t #导入时间模块,调用对象t 2 3 class Mytimer(): 4 def __init__(self): 5 self.unit = ['年','月','天','小时','分钟','秒'] 6 self.prpt = "未开始计时" 7 self.lasted = [] 8 self.begin = 0 #属性 9 self.end = 0 10 def __str__(self): 11 return self.prpt 12 13 __repr__ = __str__ 14 15 def __add__(self,other): #重写加法操作符,运行时间相加 16 prpt = "总共运行了" 17 result = [] 18 for index in range(6): 19 result.append(self.lasted[index] + other.lasted[index]) 20 if result[index]: 21 prpt += (str(result[index]) + self.unit[index]) 22 return prpt 23 24 #开始计时 25 def start(self): #方法,属性名和方法名不能相同 26 if not self.stop: 27 self.prpt = ("提示:请先调用stop()停止计时!") 28 else: 29 self.begin = t.localtime() 30 print('计时开始...') 31 32 #停止计时 33 def stop(self): 34 if not self.begin: 35 print('提示:请先调用start()进行计时!') 36 else: 37 self.end = t.localtime() 38 self._calc() 39 print('计时结束!') 40 41 #内部方法,计算运行时间 42 def _calc(self): 43 self.prpt = "总共运行了" 44 for index in range(6): 45 self.lasted.append(self.end[index] self.begin[index]) 46 if self.lasted[index]: 47 self.prpt += (str(self.lasted[index]) + self.unit[index]) 48 #为下一轮计时初始化变量 49 self.begin = 0 50 self.end = 0 51 52 >>> t1 = Mytimer() 53 >>> t1.stop() 54 提示:请先调用start()进行计时! 55 >>> t1.start() 56 计时开始... 57 >>> t1.stop() 58 计时结束! 59 >>> t1 60 总共运行了4秒 61 >>> t2 = Mytimer() 62 >>> t2.start() 计时开始... 64 >>> t2.stop() 65 计时结束! 66 >>> t2 67 总共运行了4秒 68 >>> t1 + t2 69 '总共运行了8秒'

进阶定制

?如果开始计时的时间是(2022年2月22日16:30:30),停止时间是(2025年1月23日15:30:30),那按照我们用停止时间减开始时间的计算方式就会出现负数(3年1月1天1小时),你应该对此做一些转换。

?现在的计算机速度都非常快,而我们这个程序最小的计算单位却只是秒,精度是远远不够的。



上一篇:Python基础入门学习笔记 043 魔法方法:算术运算2

下一篇:Python基础入门学习笔记 045 魔法方法:属性访问


Python
Copyright © 2002-2019 k262电脑网 www.k262.cn 皖ICP备2020016292号
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!QQ:251442993 热门搜索 网站地图