鱼C论坛

 找回密码
 立即注册
查看: 2169|回复: 0

[技术交流] 《零基础入门学习python》044笔记:魔法方法—简单定制

[复制链接]
发表于 2017-9-18 22:00:42 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
知识点一:__str__函数:简单明了,就是用来输出字符串的丫
  1. class A():
  2.         def __str__(self):
  3.                 return "汪蛋加油!"
  4.         
  5. >>> a = A()
  6. >>> print(a)
  7. 汪蛋加油!
复制代码
可见要用print(a)才能输出__str__的返回值。

知识点二:__repr__函数:简单明了,就是用来输出字符串的丫
与__str__函数略有不同,如下
  1. class B():
  2.         def __repr__(self):
  3.                 return "汪蛋加油!"
  4.         
  5. >>> b = B()
  6. >>> b
  7. 汪蛋加油!
  8. >>> print(b)
  9. 汪蛋加油!
  10. >>>
复制代码
比__str__好像厉害一些。

知识点三:类的方法名如果和属性名一致的话,属性会覆盖了方法
  1. class A():
  2.     def __init__(self):
  3.         self.lala = 0
  4.         
  5.     def lala(self):
  6.         print("这是拉拉!")
复制代码
知识点四:下面是小甲鱼课堂讲解的定时器:
  1. import time as t

  2. class MyTimer():
  3.     def __init__(self):
  4.         self.unit = ['年', '月', '天', '小时', '分钟', '秒']
  5.         self.prompt = "未开始计时!"
  6.         self.lasted = []
  7.         self.begin = 0
  8.         self.end = 0
  9.    
  10.     def __str__(self):
  11.         return self.prompt
  12.    
  13.     __repr__ = __str__

  14.     def __add__(self, other):
  15.         prompt = "总共运行了"
  16.         result = []
  17.         for index in range(6):
  18.             result.append(self.lasted[index] + other.lasted[index])
  19.             if result[index]:
  20.                 prompt += (str(result[index]) + self.unit[index])
  21.         return prompt
  22.                            
  23.     #开始计时
  24.     def start(self):
  25.         self.begin = t.localtime()
  26.         self.prompt = "请先调用stop()停止计时!"
  27.         print ("开始计时...")

  28.     #停止计时
  29.     def stop(self):
  30.         if not self.begin:
  31.             print("请先调用start()开始计时!")
  32.         else:
  33.             self.end = t.localtime()
  34.             self.__cala__()
  35.             print("计时结束!")

  36.     #内部方法,计算运行时间
  37.     def __cala__(self):
  38.         self.lasted = []
  39.         self.prompt = "总共运行了"
  40.         for index in range(6):
  41.             self.lasted.append(self.end[index] - self.begin[index])
  42.             if self.lasted[index]:
  43.                 self.prompt += (str(self.lasted[index]) + self.unit[index])
  44.         # 为下一轮计时初始化变量
  45.         self.begin = 0
  46.         self.end = 0
复制代码
可实现的功能如下:
  1. >>> t1 = MyTimer()
  2. >>> t1
  3. 未开始计时!
  4. >>> t1.stop()
  5. 请先调用start()开始计时!
  6. >>> t1.start()
  7. 开始计时...
  8. >>> t1.stop()
  9. 计时结束!
  10. >>> t2 = MyTimer()
  11. >>> t2.start()
  12. 开始计时...
  13. >>> t2.stop()
  14. 计时结束!
  15. >>> t1 + t2
  16. '总共运行了8秒'
复制代码

最后,感谢小甲鱼!!!


本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-15 21:23

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表