鱼C论坛

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

[已解决]类对象问题

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

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

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

x
求问为啥第三行第五行要加“int.”啊。。。

class New_int(int):
        def __add__(self,other):
                return int.__sub__(self,other)
        def __sub__(self,other):
                return int.__add__(self,other)
最佳答案
2020-4-12 15:32:36
int. 表示 __sub__ 和 __add__ 是 类 int 的 成员函数
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-4-12 15:32:36 | 显示全部楼层    本楼为最佳答案   
int. 表示 __sub__ 和 __add__ 是 类 int 的 成员函数
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-4-12 15:39:41 | 显示全部楼层
  1. import pprint

  2. print(pprint.pprint(dir(int)))
复制代码


你打印出来看下,
New_int继承int,  
int里面有__sub__ ,__add__

你写的代码意思是重写 父类,__add__  方法,但是返回值直接是父类的 __sub__
  1. class New_int(int):
  2.     def __add__(self, other):
  3.         return int.__sub__(self, other)

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

  6. a = New_int(5)
  7. b = New_int(3)
  8. print(a + b)
复制代码



如果不加int ,换成super也可以的

  1. class New_int(int):
  2.     def __add__(self, other):
  3.         return super().__sub__(other)

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

  6. a = New_int(5)
  7. b = New_int(3)
  8. print(a + b)
复制代码

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-6-14 15:59

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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