鱼C论坛

 找回密码
 立即注册
查看: 924|回复: 3

[已解决]45讲魔法方法——简单定制计时器

[复制链接]
发表于 2020-6-1 10:57:29 | 显示全部楼层 |阅读模式

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

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

x
  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.     __repr__ = __str__

  13.     def __add__(self,other):
  14.         prompt = '总共运行了'
  15.         result = []
  16.         for index in range(6):
  17.             result.append(self.lasted[index] + other.lasted[index])
  18.             if result[index]:
  19.                 prompt += (str(result[index]) + self.unit[index])
  20.         return prompt

  21.    
  22.     # 开始计时
  23.     def start(self):
  24.         self.begin = t.localtime()
  25.         self.prompt = '提示:请先调用stop()停止计时!'
  26.         print('计时开始...')

  27.     # 停止计时
  28.     def stop(self):
  29.         if not self.begin: #begin初始值为0,not 0为真
  30.             print('提示:请先调用start()开始计时!')
  31.         else:
  32.             self.end = t.localtime()
  33.             self._calc()
  34.             print('计时结束...')

  35.     #内部方法,计算运行时间
  36.     def _calc(self):
  37.         self.lasted = []
  38.         self.prompt = '总共运行了'
  39.         for index in range(6):
  40.             self.lasted.append(self.end[index] - self.begin[index])
  41.             if self.lasted[index]:
  42.                 self.prompt += (str(self.lasted[index]) + self.unit[index])

  43.         # 为下一轮计时初始化变量
  44.         self.begin = 0
  45.         self.end = 0
  46.         
复制代码


想问下以下代码中:    __repr__ = __str__是什么意思?
def __str__(self):
        return self.prompt

    __repr__ = __str__


最佳答案
2020-6-1 11:03:31
等于直接重新两种魔法方法,而且功能都是返回 self.prompt 参数

__repr__ , __str__ 他们的具体可以看下这个文章,我当时就是靠这个理解的 , 讲的很细致

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

使用道具 举报

发表于 2020-6-1 11:03:31 | 显示全部楼层    本楼为最佳答案   
等于直接重新两种魔法方法,而且功能都是返回 self.prompt 参数

__repr__ , __str__ 他们的具体可以看下这个文章,我当时就是靠这个理解的 , 讲的很细致

https://zhuanlan.zhihu.com/p/130442206
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-6-1 11:29:23 | 显示全部楼层
Twilight6 发表于 2020-6-1 11:03
等于直接重新两种魔法方法,而且功能都是返回 self.prompt 参数

__repr__ , __str__ 他们的具体可以看 ...

基本看懂了,在这段代码中把 __str__赋值给__repr__,意思是把这两个方法相等吗?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-6-1 11:34:59 | 显示全部楼层
jump_p 发表于 2020-6-1 11:29
基本看懂了,在这段代码中把 __str__赋值给__repr__,意思是把这两个方法相等吗?

把__str__ 赋值给 __repr__ 覆盖原本的 __repr__ 功能
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-6-21 00:41

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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