shengjiujiu 发表于 2020-4-12 15:28:30

类对象问题

求问为啥第三行第五行要加“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 的 成员函数

raimond 发表于 2020-4-12 15:39:41

import pprint

print(pprint.pprint(dir(int)))

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

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

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

a = New_int(5)
b = New_int(3)
print(a + b)


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

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

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

a = New_int(5)
b = New_int(3)
print(a + b)
页: [1]
查看完整版本: 类对象问题