class new_int (int): # Defines a new class that inherits the Int class def __add__ (self , other): # override + Operator # __add__ is the behavior of + in int return int.__sub__ (self,other) # override the addition operator to invoke the subtraction operator inside the Int class def __sub__ (Self,other): return int. (Self,other) # above is a little prank. The names of addition and subtraction are interchanged.
1 >>> a=new_int (5)2 >>> b=new_int (3)3 >>> A + b 4 2
above is to call the unbound parent class method.The following is the use of the Super function
class new_int (int): # Defines a new class that inherits the Int class def __add__ (self , other): # override + Operator # __add__ is the behavior of + in int return super. __sub__ (Self,other) # The addition operator that is overridden calls the subtraction operator inside the Int class. 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 +Btraceback (most recent): File"<pyshell#12>", Line 1,inch<module>a+b File"c:/users/administrator/desktop/new.py", Line 3,inch __add__ returnSuper.__sub__(Self,other)#The overridden addition operator calls the subtraction operator inside the Int classAttributeerror:type Object'Super'has no attribute'__sub__'
Can be seen when using super when the error message that Super No __sub__ .... But I don't know why. No relevant information was found on the Internet. When you learn more, take a look.
1 classint (int):2 def __add__(self,other):3 returnInt.__sub__(Self,other)4 5 " "def __sub__ (self,other):6 return int.__add__ (self,other)" "7 #the above two overrides can only be rewritten at the same time, otherwise, will be an error ....8 #when you write the second add, the system does not know that it will be your rewrite add and then the program crashes.
Call the unbound parent class method and choose between using the supper function.