鱼C论坛

 找回密码
 立即注册
查看: 800|回复: 2

[已解决]MyTimer运行时出错,显示unsupported operand type(s)

[复制链接]
发表于 2020-4-12 16:34:05 | 显示全部楼层 |阅读模式

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

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

x
代码:
  1. import time as t


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

  10.     def __str__(self):
  11.         return self.prompt  

  12.     def __add___(self,other):   
  13.                                 
  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.     __repr__=__str__

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

  29.     #停止计时
  30.     def stop(self):
  31.         if not self.begin:
  32.             print("提示:请先使用start()进行计时")
  33.         else:
  34.             self.end=t.localtime()
  35.             self._calc()   
  36.             print("计时结束")


  37.     #内部方法,计算运行时间
  38.     def _calc(self):
  39.         
  40.         self.lasted=[]
  41.         self.prompt="总共运行了"
  42.         for index in range(6) :
  43.             self.lasted.append(self.end[index]-self.begin[index])
  44.             
  45.             if self.lasted[index]:  
  46.                 self.prompt+=(str(self.lasted[index])+self.unit[index])
  47.         #为下一轮计时进行初始化
  48.         self.begin=0
  49.         self.end=0
  50.         



  51.                
  52.       
复制代码


结果显示:t1=MyTimer()
>>> t1.start()
计时开始
>>> t1.stop()
计时结束
>>> t1
总共运行了10秒
>>> t2=MyTimer()
>>> t2.start()
计时开始
>>> t2.stop()
计时结束
>>> t2
总共运行了11秒
>>> t1+t2
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    t1+t2
TypeError: unsupported operand type(s) for +: 'MyTimer' and 'MyTimer'
>>>
最佳答案
2020-4-12 16:35:41
那个__add__,后面多了一个下划线。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-4-12 16:35:41 | 显示全部楼层    本楼为最佳答案   
那个__add__,后面多了一个下划线。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-4-12 19:03:44 | 显示全部楼层
qiuyouzhi 发表于 2020-4-12 16:35
那个__add__,后面多了一个下划线。

真的是,谢谢!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-6-14 16:14

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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