鱼C论坛

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

[已解决]小甲鱼《零基础入门学习python》044讲,魔法方法repr和add不生效

[复制链接]
发表于 2022-8-18 17:08:54 | 显示全部楼层 |阅读模式

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

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

x
参考课程讲解的内容,利用time.time的方式进行课程作业完成,但遇到两个问题
1、__repr__ = __str__不生效
        使用此语法后,直接输入对象名称并不会进行打印

2、__add__不生效
        重写add方法后,仍然提示错误

代码及报错如下

  1. class Myime:
  2.         def __init__(self):
  3.             self.start_time = 0
  4.             self.end_time = 0
  5.             self.result = 0

  6.         def __str__(self):
  7.             if not self.start_time and not self.end_time:
  8.                 return '未开始计时!'
  9.             elif not self.end_time:
  10.                 return '提示:请先调用stop()开始计时!'
  11.             elif self.start_time and self.end_time:
  12.                 self.result = self.end_time - self.start_time

  13.                 return f'总共运行了{self.result}秒'

  14.         def start(self):
  15.             self.start_time = time.time()
  16.             print("计时开始……")

  17.         def stop(self):
  18.             if not self.start_time:
  19.                 print('提示:请先调用start()开始计时!')
  20.             else:
  21.                 self.end_time = time.time()
  22.                 print("计时结束!")

  23.         # 利用赋值的方式使得直接打印
  24.         __repr__ = __str__

  25.         def __add__(self, other):
  26.             temp = self.result + other.result
  27.             return f'总共运行了{temp}秒'

  28.         
  29. t1 = Mytime()
  30. t1
  31. <__main__.Mytime object at 0x000001765AF3E020>
  32. print(t1)
  33. 未开始计时!
  34. t1.start()
  35. 计时开始……
  36. print(t1)
  37. 提示:请先调用stop()开始计时!
  38. t1
  39. <__main__.Mytime object at 0x000001765AF3E020>
  40. t1.stop()
  41. 计时结束!
  42. print(t1)
  43. 总共运行了15.581618547439575秒
  44. t2 = Mytime()
  45. t2.start()
  46. 计时开始……
  47. print(t2)
  48. 提示:请先调用stop()开始计时!
  49. t2.stop()
  50. 计时结束!
  51. t1+t2
  52. Traceback (most recent call last):
  53.   File "<pyshell#30>", line 1, in <module>
  54.     t1+t2
  55. TypeError: unsupported operand type(s) for +: 'Mytime' and 'Mytime'
  56. print(t1+t2)
  57. Traceback (most recent call last):
  58.   File "<pyshell#31>", line 1, in <module>
  59.     print(t1+t2)
  60. TypeError: unsupported operand type(s) for +: 'Mytime' and 'Mytime'
复制代码
最佳答案
2022-8-18 17:18:09
class Mytime单词写错了
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2022-8-18 17:18:09 | 显示全部楼层    本楼为最佳答案   
class Mytime单词写错了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-8-18 17:22:37 | 显示全部楼层
本帖最后由 tommyyu 于 2022-8-18 17:23 编辑

你这个定义的是Myime, 运行的时候为什么变成了Mytime
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-8-18 22:07:42 | 显示全部楼层
感谢两位!!脑残了!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-4-27 09:56

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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