Inverse operation:
Called when the left operand does not support a response operation
such as: Object (A+B), if the A object has a __add__ method, the __radd__ of the B object is not called
The __radd__ method of B is called only if the __add__ method of the A object is not implemented or does not support the corresponding operation.
such as:>>> class Nint (int):
... def __radd__ (self,other):
... return int.__sub__ (self,other)
...
>>> a = Nint (5)
>>> B = Nint (3)
>>> A + b
2
>>> 1 + B When 1 did not find the response to the action to press B, so it was executed B's
2
such as:>>> class Nint (int):
... def __rsub__ (Self,other)
... return int.__sub__ (self,other)
...
>>> a = Nint (5)
>>> 3-a shouldn't be-2? Why is it?
2
such as:>>> class Nint (int):
... def __rsub__ (self,other):
... return int.__sub__ (other,self) Just change the position of the parameter here, the result is different
...
>>> a = Nint (5)
>>> 3-a
-2
Unary operators:
_neg_ (self) defines the behavior of a positive sign: +x
_pos_ (self) defines the behavior of the minus sign:-X
_abs_ (self) defines the behavior when being called by ABS ()
_invert_ (self) defines the bitwise negation behavior: ~x
Practice:
1. Define a class that automatically determines how many parameters are passed in when the class is instantiated and displays
such as:>>> class C:
... def __init__ (Self,*args):
... if not args:
... print ("WU")
.. else:
... print ("%d,:"% len (args)),
... for each in args:
.. print (each),
...
043 Magic Methods: arithmetic Operations 2