类对象问题
求问为啥第三行第五行要加“int.”啊。。。class New_int(int):
def __add__(self,other):
return int.__sub__(self,other)
def __sub__(self,other):
return int.__add__(self,other) int. 表示 __sub__ 和 __add__ 是 类 int 的 成员函数 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]