鱼C论坛

 找回密码
 立即注册
查看: 3393|回复: 5

self,other疑问?

[复制链接]
发表于 2016-5-18 08:43:12 | 显示全部楼层 |阅读模式

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

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

x
def __add__(self):
        result = []
        for index in range(6):
            result.appeng(self.lasted[index] + other.lasted[index])

最后 self other 是指第一个第二个参数吗?  如果有 第三个参数是什么?
还是说 用 other 相当于所有参数相加?
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-5-18 10:33:00 | 显示全部楼层
这是类定义中的一段代码吧?self指的是类对象本身,至于othe,因为没看到全部的代码,不知道是什么意思,在代码其他的地方肯定是有定义的r
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-5-18 21:01:53 | 显示全部楼层
vpo1 发表于 2016-5-18 10:33
这是类定义中的一段代码吧?self指的是类对象本身,至于othe,因为没看到全部的代码,不知道是什么意思,在 ...
  1. import time as t

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

  10.     def __str__(self):
  11.         return self.prompt
  12.    
  13.     __repr__ = __str__

  14.     def __add__(self):
  15.         prompt= '总共运行了'
  16.         result = []
  17.         for index in range(6):
  18.             result.appeng(self.lasted[index] + other.lasted[index])
  19.             if result[index]:
  20.                 prompt += (str(result[index])+self.unit[index])
  21.         return prompt
  22.             
  23.    
  24.     #开始计时
  25.     def start(self):
  26.         self.begin = t.localtime()
  27.         print('计时开始。。。')

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

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


这是全码 也没有 other
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2016-5-18 22:55:35 | 显示全部楼层
哦,抱歉第一次看忽视了,这是类中的特殊方法,你可以看到类中在_cal方法中有一句,self.prompt += (str(self.lasted[index])+self.unit),但是我们看到lasted定义的是一个列表,而unit = ['年' , '月' , '日' , '小时' , '分钟' , '秒'],这个怎么能直接相加呢?原因就是定义了__add__方法,在这个特殊的方法中定义了当出现a+b的时候,这个+如何解释。在这个特殊的方法中self无需多解释了,other就是+这个方法的右侧对象
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2016-5-19 13:44:37 | 显示全部楼层
学习
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-5-22 15:39:19 | 显示全部楼层
来学习下
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2026-2-21 02:45

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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