鱼C论坛

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

[已解决]python 中add魔法方法重写

[复制链接]
发表于 2020-10-16 17:03:44 | 显示全部楼层 |阅读模式

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

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

x
  1. class A(int):
  2.     def __add__(self, other):
  3.         return int.__add__(self, other)
  4.     def __sub__(self, other):
  5.         return int.__sub__(self, other)
复制代码


重写int方法时,上面是正确的,但是下面却是错误的

  1. class A(int):
  2.     def __add__(self, other):
  3.         return super().__add__(self, other)
  4.     def __sub__(self, other):
  5.         return super().__sub__(self, other)
复制代码

  1. a = A(2)
  2. b = A(3)

  3. a + b

  4. TypeError: expected 1 arguments, got 2
复制代码


为什么不能使用super呢?
最佳答案
2020-10-16 17:13:38
super() 函数是用于调用父类的
比如这样
  1. class B(int):
  2.     def __add__(self, other):
  3.         return int.__add__(self, other)

  4.     def __sub__(self, other):
  5.         return int.__sub__(self, other)


  6. class A(B):
  7.     def __add__(self, other):
  8.         return super().__add__(other)

  9.     def __sub__(self, other):
  10.         return super().__sub__(other)


  11. if __name__ == '__main__':
  12.     a = A(2)
  13.     b = A(3)

  14.     print(a + b)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-10-16 17:13:38 | 显示全部楼层    本楼为最佳答案   
super() 函数是用于调用父类的
比如这样
  1. class B(int):
  2.     def __add__(self, other):
  3.         return int.__add__(self, other)

  4.     def __sub__(self, other):
  5.         return int.__sub__(self, other)


  6. class A(B):
  7.     def __add__(self, other):
  8.         return super().__add__(other)

  9.     def __sub__(self, other):
  10.         return super().__sub__(other)


  11. if __name__ == '__main__':
  12.     a = A(2)
  13.     b = A(3)

  14.     print(a + b)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-10-16 17:18:33 From FishC Mobile | 显示全部楼层
本帖最后由 hrp 于 2020-10-16 17:31 编辑
  1. class A(int):
  2.     def __add__(self, other):
  3.         return super().__add__(other)
  4.     def __sub__(self, other):
  5.         return super().__sub__(other)
  6.         
  7. a=A(2)
  8. b=A(3)
  9. print(a+b)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-5-3 01:05

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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