|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- class A(int):
- def __add__(self, other):
- return int.__add__(self, other)
- def __sub__(self, other):
- return int.__sub__(self, other)
复制代码
重写int方法时,上面是正确的,但是下面却是错误的
- class A(int):
- def __add__(self, other):
- return super().__add__(self, other)
- def __sub__(self, other):
- return super().__sub__(self, other)
复制代码
- a = A(2)
- b = A(3)
- a + b
- TypeError: expected 1 arguments, got 2
复制代码
为什么不能使用super呢?
super() 函数是用于调用父类的
比如这样
- class B(int):
- def __add__(self, other):
- return int.__add__(self, other)
- def __sub__(self, other):
- return int.__sub__(self, other)
- class A(B):
- def __add__(self, other):
- return super().__add__(other)
- def __sub__(self, other):
- return super().__sub__(other)
- if __name__ == '__main__':
- a = A(2)
- b = A(3)
- print(a + b)
复制代码
|
|