Decorators are an important part of Python.
They are functions that modify the functionality of other functions. This helps keep our code shorter.
So where to use them, what areas of the decorators will make the code cleaner.
! [](https://pic2.zhimg.com/80/v2-01086bc3cff2c33d3ab80a0f09a5883b_720w.png)
1\. Definition of decorator
A function that adds extra functionality to an existing function, which is essentially a closure function. Features of decoration:
1, do not modify the existing function source code
2. Do not modify the call method of existing functions
3. Add extra functionality to existing functions
4. Closures and decorators:
A closure function is called a decorator if it has one and only arguments of function type.
Code should be written in accordance with the open and closed principle, which states that the implemented function code cannot be modified, but can be extended.
2\. Sample code for decorators
Def decorator(func): def inner(): return inner def comment(): Print (' comment ') # print(' comment ') # print(' comment ') # print(' comment ') # print(' comment ') # print(' comment ') # print(' comment ') #Copy the code
3\. Grammar sugar writing of decorator
If you have more than one function that needs to add login authentication, it can be cumbersome to write func = decorator(func) code to decorate the existing function each time.
Python provides a simpler way to decorate functions, called syntactic sugar, which is written in the form @ decorator names. It is also possible to decorate existing functions with syntactic sugar.
Def decorator(func): def inner(): Print (' added login authentication ') func() return inner @decorator # comment = decorator(comment) decorator syntax sugar encapsulates this code Left comment=inner def comment(): print(' comment ')Copy the code
4\. Execution timing of decorators
The decorator executes immediately after the current module is loaded to decorate the existing functions.
Def decorator(func): print(' the decorator executes ') def inner(): Print (' added login authentication ') func() return inner @decorator # comment = decorator(comment) decorator syntax sugar encapsulates this code Left comment=inner def comment(): print(' comment ')Copy the code
5\. Use of Decorators 5.1 Use scenarios of decorators
1. Function execution time statistics.
2. Output log information.
5.2 Decorator to implement the statistics of the execution time of existing functions
import time def decorator(func): def inner(): Begin = time.time() func() end = time.time() result = end-begin print(f') {result}') return inner @decorator def work(): for i in range(10000): print(i) work()Copy the code
6\. Use of general purpose decorators
General-purpose decorators: You can decorate any type of function. When decorating an existing function with a decorator, the type of the inner function is the same as the type of the existing function to be decorated.
6.1 Decorates functions with arguments
def decorator(func): def inner(num1, num2): Decorator def add_num(num1, num2): print(' trying to add ') func(num1, num2) return decorator def add_num(num1, num2): Result = num1 + num2 print(f' result = {result}') add_num(1, 2)Copy the code
6.2 Decorates functions with parameters and return values
def decorator(func): def inner(num1, num2): Num = func(num1, num2) return num return inner @decorator def add_num(num1, num2): Result = num1 + num2 return result result = add_num(1, 2) print(f' result = {result}')Copy the code
7\. Use of multiple decorators
Multi-decorator decorating process: a decorating process from the inside out, executing the inside decorator first and then the outside decorator.
Def make_div(func): print('make_div ') def inner(): Result = '<div>' + func() + '</div>' return result return inner def make_p(func): print('make_p ') def inner(): Result = '<p>' + func() + '</p>' return result return inner # Content = make_p(content), interior decorator done, content = make_p.inner # content = make_div(make_p.inner) @make_div @make_p def content(): C = content() print(c)Copy the code
8\. Decorator with parameters
Decorator with parameters is when you use decorator to decorate a function you can pass in the specified parameters,
Syntax: @ Decorator (parameter,…) .
Using a decorator with arguments wraps a function around the decorator that receives arguments and returns decorators, because the @ symbol needs to be used with the decorator instance.
Def decorator(func): def inner(a, b): if flag == '+': Print (' trying to add ') elif flag == '-': Print (' trying to perform subtraction ') func(a, Return decorator @return_decorator('+') # decorator = return_decorator('+'), @decorator => add_num = decorator(add_num) def add_num(a, b): result = a + b print(result) @return_decorator('-') def sub_num(a, b): result = a - b print(result) add_num(1, 2) sub_num(1, 2)Copy the code
9. Application scenarios of decorators
Collect operation or error logs of functions.
2. Verify the permission to use the function.
3. Calculate the running time of the function.
4, in the ORM/DB model operation, through the attribute method to dynamically obtain the associated data.
5. Caching of function data.
6. Customize the input and output of functions (serialization and deserialization).