Python decorator and example login verification before payment

1. Features of the decorator:

(1) As long as it is a decorator, the function will appear as a parameter, that is, def function B (function A)

(2) It must have the characteristics of closure, as follows, define a decorator

2. Use decorators

(1) The house function is below decorate, and house will act as the decorated function

(2) Pass the decorated function house as a parameter to the decorator decorate

(3) Even if you do not write the calling function house(), the bottom layer will silently execute the decorate function

(4) Assign the return value to house

(5) At this time, I call house(), which is actually to call wrapper()

The specific process: first pass house to func, that is, func = house, then call the code inside, load variable a, print, load the wrapper function, print again, and finally return to the wrapper function. We see that there is nothing to pick up the wrapper. But the bottom layer uses the function house with the same name to replace the wrapper function by default, see the red box below.


Recommendation: 020 is continuously updated, the small circle of boutiques has new content every day, and the concentration of dry goods is extremely high.
There are everything you want to make connections and discuss technology!
Be the first to join the group and outperform your peers! (There is no fee for joining the group)
Click here to communicate and learn with Python developers.
Group number: 745895701
application and delivery :
Python software installation package, Python actual combat tutorial,
free collection of materials, including Python basic learning, advanced learning, crawling, artificial intelligence, automated operation and maintenance, automated testing, etc.

Insert picture description here

3. Decorator with parameters

4. Universal decorator

Now if you want to pass one parameter, multiple parameters, or no parameters, the decorator can accept it. You need to use the previous variable parameters and unpacking. *args, **kwargs.

5. If it is a multi-layer decorator, decorate the nearest one first.

6. The decorator with parameters is three layers

The first layer: responsible for receiving the parameters of the decorator

The second layer: responsible for receiving functions

The third layer: responsible for receiving the parameters of the function

Calling house() is equivalent to calling wrapper()

7. Examples of payment login verification

Guess you like

Origin blog.csdn.net/Python_xiaobang/article/details/112368025