鱼C论坛

 找回密码
 立即注册
查看: 1830|回复: 1

[迷途问路] 魔法方法

[复制链接]
发表于 2020-8-28 22:15:57 | 显示全部楼层 |阅读模式

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

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

x
不知道为啥运算t1+t2时总是出现typeerror的提醒,有哪位大神知道的,可以告诉我嘛,十分感谢

  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:
  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
复制代码


====================================== RESTART: C:\Users\john\Desktop\time.py =====================================
>>> t1 = MyTimer()
>>> t1
未开始计时!
>>> t1.stop()
提示:请先调用start()开始计时!
>>> t1.start()
计时开始...
>>> t1.stop()
计时结束...
>>> t1
总共运行了3秒
>>> t2 = MyTimer()
>>> t2.start()
计时开始...
>>> t2.stop()
计时结束...
>>> t2
总共运行了5秒
>>> t1 + t2
Traceback (most recent call last):
  File "<pyshell#133>", line 1, in <module>
    t1 + t2
  File "C:\Users\john\Desktop\time.py", line 19, in __add__
    for index in range[6]:
TypeError: 'type' object is not subscriptable
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-8-31 23:15:43 From FishC Mobile | 显示全部楼层
type就是类型错误,
你看一下22行,str类型应该是int类型吧
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-24 17:19

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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