class New_int(int):   # 定义一个新的类  继承 int 类
    def __add__(self,other):   # 重写 + 运算符 # __add__ 就是 int 中 +  的行为
        return int.__sub__(self,other)    # 重写的 加法运算符 调用 int类 里面的 减法运算运算符

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


# 上面的是一个小小的恶作剧 . 把加法和减法的名称进行了互换.
1 >>> a=New_int(5)
2 >>> b=New_int(3)
3 >>> a+b
4 2

 

上面的是调用未绑定的父类方法.

下面是使用super函数

class New_int(int):   # 定义一个新的类  继承 int 类
    def __add__(self,other):   # 重写 + 运算符 # __add__ 就是 int 中 +  的行为
        return super.__sub__(self,other)    # 重写的 加法运算符 调用 int类 里面的 减法运算运算符

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


# 上面的是一个小小的恶作剧 . 把加法和减法的名称进行了互换.
=============== RESTART: C:/Users/Administrator/Desktop/new.py ===============
>>> a=New_int(5)
>>> b=New_int(3)
>>> a+b
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    a+b
  File "C:/Users/Administrator/Desktop/new.py", line 3, in __add__
    return super.__sub__(self,other)    # 重写的 加法运算符 调用 int类 里面的 减法运算运算符
AttributeError: type object 'super' has no attribute '__sub__'

 

1 class int(int):
2     def __add__(self,other):
3         return int.__sub__(self,other)
4 
5     '''def __sub__(self,other):
6         return int.__add__(self,other)'''
7 #   上面的 两个重写只能在同一时间内重写一个 , 不然的话  , 就会报错.....
8 #   当写第二个的  add 的时候 系统不知道 会认为是 你重写的 add 然后程序就崩溃了.  

 

相关文章:

  • 2021-11-17
  • 2022-12-23
  • 2021-11-16
  • 2021-07-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-13
猜你喜欢
  • 2021-08-30
  • 2021-11-09
  • 2022-12-23
  • 2021-12-21
  • 2022-12-23
  • 2022-12-23
  • 2022-02-10
相关资源
相似解决方案