Summarize the magic methods commonly used in Python

Time:2021-12-31
catalogue
  • 1、 Magic method of arithmetic operator
  • 2、 Magic methods related to inverse operation
  • 3、 Incremental assignment operation
  • 4、 Unary operator

1、 Magic method of arithmetic operator

  • python2. After 2, classes and types are unified. The way is to convert BIFS such as int (), float (), str (), list (), tuple () into factory functions (class objects)
  • Give the magic method corresponding to the following arithmetic operators. Both the front and back are double underlined, indicating that it is a magic method
operator Corresponding magic method Chinese Notes
+ __ add__(self, other) addition
__ sub__(self, other) subtraction
* __ mul__(self, other) multiplication
/ __ truediv__(self, other) True Division
// __ floordiv__(self, other) Integer division
% __ mod__(self, other) Remainder Division
divmod(a, b) __ divmod__(self, other) Combining the result of divisor and remainder operation, the return value of divmod (a, b) is a tuple (A / / B, a% B)
** __ pow__(self, other[,modulo]) Take the remainder of modulo to the other power of self
<< __ lshift__(self, other) Shift left by bit
>> __ rshift__(self, other) Shift right by bit
& __ and__(self, other) Bitwise and operation
^ __ xor__(self, other) Bitwise exclusive or operation (both 0 and 1)
__ or__(self, other) Bitwise OR operation (1 if there is 1)
  • eg:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
>>> type(len)
<class 'builtin_function_or_method'>            #Ordinary BIF
>>> type(int)
<class 'type'>             #Factory functions (class objects), when called, actually create a corresponding instance object
>>> type(dir)
<class 'builtin_function_or_method'>
>>> type(list)
<class 'type'>
 
>>> a = int('123')        #Create a corresponding instance object a
>>> b = int('345')
>>> a + b              #Python adds two objects
468
  • Eg: for example, the following defines a unique class:

Inherit int and override__ add__ method

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
>>> 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(3)
>>> b = New_int(5)
>>> a + b    #When two objects are added, trigger__ add__ (self, other) method
-2
>>> a - b
8
>>>
 
example2: incorrect writing will cause infinite recursion
>>> class New_int(int):
    def __add__(self,other):
        return (self + other) 
    def __sub__(self,other):
        return (self - other)
 
 
>>> class New_int(int):
    def __add__(self,other):
        return (int(self) + int(other))       #Cast self and other to integers, so there is no trigger for adding two objects__ add__ () method
    def __sub__(self,other):
        return (int(self) - int(other))
 
    
>>> a = New_int(3)
>>> b = New_int(5)
>>> a + b
8

2、 Magic methods related to inverse operation

  • Magic methods related to inverse operation
Magic method definition
__ radd__(self, other) Define the behavior of addition: + (called when the left operand does not support the corresponding operation)
__ rsub__(self, other) Define the behavior of subtraction: – (called when the left operand does not support the corresponding operation)
__ rmul__(self, other) Define the behavior of multiplication: * (called when the left operand does not support the corresponding operation)
__ rtruediv__(self, other) Define the behavior of true Division: / (called when the left operand does not support the corresponding operation)
__ rfloordiv__(self, other) Define the behavior of integer division: / / (called when the left operand does not support the corresponding operation)
__ rmod__(self, other) Define the behavior of modulus algorithm:% (called when the left operand does not support the corresponding operation)
__ rdivmod__(self, other) Defines the behavior when called by divmod() (called when the left operand does not support the corresponding operation)
__ rpow__(self, other) Defines the behavior when called by power() or * * operation (called when the left operand does not support the corresponding operation)
__ rlshift__(self, other) Define the behavior of bitwise left shift: < < (called when the left operand does not support the corresponding operation)
__ rrshift__(self, other) Define the behavior of bitwise right shift: > > (called when the left operand does not support the corresponding operation)
__ rand__(self, other) Defines the behavior of bitwise and operations: & (called when the left operand does not support the corresponding operation)
__ rxor__(self, other) Define the behavior of bitwise XOR operation: ^ (called when the left operand does not support the corresponding operation)
__ ror__(self, other) Define the behavior of bitwise OR operation: 1 (called when the left operand does not support the corresponding operation)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
>>> class int(int):
    def __add__(self,other):
        return int.__sub__(self,other)
 
    
>>> a = int(3)
>>> b = int(2)
>>> a + b
1
 
The difference between inverse operation and arithmetic operator is that there is one more inverse operation'r'For example__ add__ The inverse operation of () corresponds to__ radd__ ()
 
>>> a + b
 
Here a is the addend and B is the addend, if the object of a__ add__ If the () method is not implemented or does not support the corresponding operation, python will automatically call B__ radd__ () method
 
example:
 
>>> class Nint(int):
    def __radd__(self,other):
        return int.__sub__(self,other)
 
    
>>> a = Nint(5)
>>> b = Nint(3)
>>> a + b      #Because the a object has__ add__ () method, so B__ radd__ () not implemented
8
 
example2
 
>>> class Nint(int):
    def __radd__(self,other):
        return int.__sub__(self,other)
 
    
>>> b = Nint(5)
>>> 3 + b         #Since 3 no__ add__ () method, so it performs the inverse operation of B__ radd__ (self, other) method, where self is the B object
2

Eg: Note: when rewriting the magic method of inverse operation, we must pay attention to the order. The result should be a negative number, so change the order.

Summarize the magic methods commonly used in Python

3、 Incremental assignment operation

Magic method of incremental assignment operation

Magic method definition
__ iadd__(self, other) Define the behavior of assignment addition:+=
__ isub__(self, other) Define the behavior of assignment subtraction:-=
__ imul__(self, other) Define the behavior of assignment multiplication:*=
__ itruediv__(self, other) Define the behavior of assignment true Division:/=
__ ifloordiv__(self, other) Define the behavior of assigning integer division://=
__ imod__(self, other) Define the behavior of assignment modulo algorithm:%=
__ ipow__(self, other) Define the behavior of the assignment power operation:**=
__ ilshift__(self, other) Define the behavior of bitwise left shift of assignment:<<=
__ irshift__(self, other) Define the behavior of bitwise right shift of assignment: > >=
__ iand__(self, other) Define the behavior of assignment bitwise and operation:&=
__ ixor__(self, other) Define the behavior of assignment XOR operation:^=
__ ior__(self, other) Define the behavior of bitwise assignment or operation:=

4、 Unary operator

  • Magic method of unary operator
Magic method definition
__ neg__(self) Defines the behavior of the plus sign: + X
__ pos__(self) Defines the behavior of the minus sign: – x
__ abs__(self) Defines the behavior when called by ABS ()
__ invert__(self) Define bitwise negation behavior: ~ x

This is the end of this article about summarizing the magic methods commonly used in Python. For more information about Python magic methods, please search the previous articles of developeppaper or continue to browse the relevant articles below. I hope you will support developeppaper in the future!