鱼C论坛

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

为啥我执行相加操作的时候,说我越界了,代码如下

[复制链接]
发表于 2016-3-17 17:25:56 | 显示全部楼层 |阅读模式

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

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

x
import time as t

class m:
    def __str__(self):
        return self.prompt

    __repr__ = __str__

    #定义时间相加
    def __add__(self,other):
        tips = '相加之后,总共运行了'
        result = []
        print(other.lasted)
        print(self.lasted)
        for index in range(6):
            result.append(self.lasted[index] + other.lasted[index])
            print(index)
            if result[index]:
                tips += (str(result[index]) + self.un[index])
        return tips
            
   
    #定义参数
    def __init__(self):
        self.begin = 0
        self.end = 0
        self.lasted = []
        self.prompt = '还没有开始计时啦,先用start好么?'
        self.un = ['年','月','天','小时','分','秒']
   
    #开始计时
    def start(self):
        self.begin = t.localtime()
        print('开始计时')

    #结束计时   
    def stop(self):
        self.end = t.localtime()
        if self.begin == 0:
            print('请先调用start()方法!!')
        else:
            self.calc()
            print('结束计时')

    #计算计时时间
    def calc(self):
        self.prompt = '总共运行了'
        lasted = []
        for index in range(6):
            lasted.append(self.end[index] - self.begin[index])
            if lasted[index]:
                self.prompt += (str(lasted[index]) + self.un[index])
                print (list(lasted))
        self.begin = 0
        self.start = 0


>>> a = m()
>>> a.start()
开始计时
>>> a.stop()
结束计时
>>> b = m()
>>> b.start()
开始计时
>>> b.stop()
结束计时
>>> a + b
[]
[]
Traceback (most recent call last):
  File "<pyshell#53>", line 1, in <module>
    a + b
  File "D:/Python34/test13.py", line 16, in __add__
    result.append(self.lasted[index] + other.lasted[index])
IndexError: list index out of range
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2016-3-17 17:26:53 | 显示全部楼层
我打印了 相加时的 lasted,都是空,不知为何
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-3-17 19:45:07 | 显示全部楼层
好吧,已结局,是我再定义calc 方法时,定义的lasted 变量时,没有增加self,所以报错了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2026-2-20 05:51

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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