Python commonly used magic methods

What is a magic method?

In Python, all methods wrapped in double underscore __ are collectively called Magic Method (magic method), which is a special method. Normal methods need to be called, but magic methods can be executed automatically without calling them.

Magic methods are automatically executed after certain events of the class or object are launched, giving the class its magical "magic power". If you want to customize your own special function class according to your own program, then you need to rewrite these methods.

Commonly used operators, for loops, and class operations in Python all run on magic methods.

Application of magic methods __init__, __new__, __del__

classPeople(object):
 # Create object
 def __new__(cls,*args,**kwargs):print("Triggered the constructor")
  ret =super().__new__(cls) #Call the parent class__new__()Method to create an object
  return ret ##Return object
 # Instantiate object
 def __init__(self, name, age):
  self.name = name
  self.age = age
  print("Initialization method")
 # Delete object
 # del object name or after program execution ends
 def __del__(self):print("Destructor method, delete object")if __name__ =='__main__':
 p1 =People('xiaoming',16)
    
Output:
Triggered the constructor
Initialization method
Destructor method, delete object

Use the __call__ method to realize Fibonacci sequence

# The Fibonacci sequence refers to such a sequence of 0,1,1,2,3,5,8,13
# Special note: The 0th item is 0, and the 1st item is the first 1. Starting from the third item, each item is equal to the sum of the first two items.
classFib(object):
 def __init__(self):
  pass
 def __call__(self,num):
  a,b =0,1;
  self.l=[]for i inrange(num):
   self.l.append(a)
   a,b= b,a+b
  return self.l
 def __str__(self):returnstr(self.l)
 __ rept__=__str__

f =Fib()print(f(10))
Output:
[0,1,1,2,3,5,8,13,21,34]

Commonly used magic methods

1. Initialization method __init__

Trigger mechanism: trigger immediately after instantiating the object
Parameters: at least one self, receiving the current object, other parameters are defined as needed
Return value: None
Role: initialize the members of the object

2. Construction method __new__

Trigger timing: Automatically trigger when the object is instantiated (in__init__Triggered before)
Parameters: at least one cls receives the current class, other parameters are determined according to the initialization method parameters
Return value: must return an object instance, if there is no return value, the result of instantiating the object is None
Role: instantiate objects
Note: The instantiated object is the underlying implementation of the Object class, and other classes inherit Object's__new__Can realize the instantiation object.

3. Destructor method __del__

Trigger timing: automatically trigger when this type of object is destroyed
Parameters: a self, accepts the current object
Return value: None
Role: close or release resources when the object is created
Note: del does not necessarily trigger the current method, only when the current object has no variable references

4.__ call__

Call the magic method of the object
Trigger timing:Triggered when the object is called as a function,Way: Object()
parameter:至少一个self接收对象,其余根据调用时parameter决定
Return value: According to the situation
Function: The complicated steps can be combined to reduce the call steps, which is convenient to use
Note: None

5.__ len__

Trigger timing: use len(Object)Trigger when
Parameters: a parameter self
Return value: must be an integer
Function: It can be set to detect the number of object members, but other arbitrary operations can also be performed
Note: The return value must be an integer, otherwise a syntax error will be reported, and the requirement is a format requirement.

6.__ str__

Trigger timing:Use print(Object)Or str(Object)Trigger when
Parameters: a self receiving object
Return value: must be a string type
Function: print (object time) to operate, get a string, usually used for shortcut operations
Note: None

7.__ repr__

Trigger timing:Using repr(Object)Trigger when
Parameters: a self receiving object
Return value: must be a string
Function: Use when converting the object to repr into a string, and can also be used for shortcut operations

8.__ bool__

Trigger timing:Use bool(Object)Trigger when
Parameters: a self receiving object
Return value: must be a boolean
Function: Determined according to the actual situation, can be used as a shortcut
note:Only suitable for operations that return boolean values

9.__ format__

Trigger timing: use string.format(Object)When triggered
Parameters: one self receiving object, one parameter receiving format{}Format in, for example:>5
return value:Must be a string
Function: The setting object can be used as a parameter of format, and the rules of custom object formatting
Note: None

Magic methods related to comparison operations


__ lt__(self, other):
Define the behavior of the less than sign: x<y calls x.lt(y)
__ le__(self, other):
Define the behavior of less than or equal signs: x<=y calls x.le(y)
__ eq__(self, other) :
Define the behavior of the equal sign: x==y calls x.eq(y)
__ ne__(self, other):
Define the behavior of unequal signs: x!=y calls x.ne(y)
__ gt__(self, other):
Define the behavior of greater than sign: x>y calls x.**gt(y)
__ ge__(self, other) :
Define the behavior of greater than or equal to: x>=y calls x.ge(y)

Magic methods related to arithmetic operations


__ add__(self, other)Define the behavior of addition:+__sub__(self, other)Define the behavior of subtraction:-__mul__(self, other)Define the behavior of multiplication:*__truediv__(self, other)Define the behavior of true division:/__floordiv__(self, other)Define the behavior of integer division://__mod__(self, other)Define the behavior of the modulo algorithm:%__divmod__(self, other)Define when divmod()Behavior when called
__ pow__(self, other[, modulo])Define when to be powered()Call or**Behavior during operation
__ lshift__(self, other)Define the behavior of bitwise left shift:<<__rshift__(self, other)Define the behavior of bitwise right shift:>>__and__(self, other)Define the behavior of bitwise AND operation:&__xor__(self, other)Define the behavior of bitwise XOR operation:^__or__(self, other)Define the behavior of bitwise OR operation:|

Magic methods related to assignment operations


__ 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 assigning true division:/=__ifloordiv__(self, other)Define the behavior of assigned integer division://=__imod__(self, other)Define the behavior of the assignment modulo algorithm:%=__ipow__(self, other[, modulo])Define the behavior of assignment exponentiation:**=__ilshift__(self, other)Define the behavior of the assignment bitwise left shift:<<=__irshift__(self, other)Define the behavior of the assignment bitwise right shift:>>=__iand__(self, other)Define the behavior of assignment bitwise AND operation:&=__ixor__(self, other)Define the behavior of assignment bitwise XOR operation:^=__ior__(self, other)Define the behavior of assignment bitwise OR operation:|=

Magic methods related to unary operations


__ pos__(self)Define the behavior of positive signs:+x
__ neg__(self)Define the behavior of the negative sign:-x
__ abs__(self)Defined as abs()Behavior when called
__ invert__(self)Define the behavior of bitwise negation:~x

Type conversion related magic methods


__ complex__(self)Defined as complex()Behavior at call time (requires proper value to be returned)
__ int__(self)Defined as int()Behavior at call time (requires proper value to be returned)
__ float__(self)Define when to be float()Behavior at call time (requires proper value to be returned)
__ round__(self[, n])When defined as round()Behavior at call time (requires proper value to be returned)
__ index(self)__        1.When the object is applied in the slice expression, implement the shaping coercion
      2. If you define a custom numeric type that may be used in slicing,You should define index
      3. If index is defined, int also needs to be defined and returns the same value

Context management related magic methods (with)

__ enter__ and __exit__

__ enter__(self)1.Define the initialization behavior when using the with statement
 2. The return value of enter is bound by the target of the with statement or the name after as

__ exit__(self, exctype, excvalue, traceback)1.Define what the context manager should do when a code block is executed or terminated
 2. Generally used to handle exceptions, clean up work, or do routine work after some code blocks are executed

Magic method related to container type

__ len__(self)Defined as len()Behavior when called (returns the number of elements in the container)
__ getitem__(self, key)Define the behavior of obtaining the specified element in the container, equivalent to self[key]__setitem__(self, key, value)Define the behavior of the specified element in the setting container, equivalent to self[key]= value
__ delitem__(self, key)Define the behavior of deleting the specified element in the container, equivalent to del self[key]__iter__(self)Define the behavior when iterating the elements in the container
__ reversed__(self)Defined when reversed()Behavior when called
__ contains__(self, item)Define the behavior when using the membership test operator (in or not in)

Recommended Posts

Python commonly used magic methods
Magic methods and uses of Python
Introduction to Python commonly used visualization libraries
Summary of Ubuntu commonly used commands
Centos7 system commonly used commands
Python commonly used magic methods
Python magic method topic
Python object-oriented magic method
Python black magic metaclass
Centos7 system commonly used commands
Python3 script programming commonly used.md
Python magic function eval () learning
A large inventory of commonly used third-party libraries in Python
Python Data Science: Regularization Methods
Python3 interface development commonly used.md
Summary of Ubuntu commonly used commands