Python decorator understanding, python decorator understanding

Source: Internet
Author: User
Tags python decorator

Python decorator understanding, python decorator understanding

 

1. Functions of the decorator

Add new functions for the decorated object without modifying the source code and calling method of the decorated object

Principles:

1. Do not modify the source code of the decorated object
2. Do not modify the call method of the decorated object

Objectives:

Add new features to the decorated object

2. Definition and use of decorator

Let's look at the following code:

The index function is used by the program to print a sentence after 1 to 5 seconds of random sleep.

Now I want to add a new function for the index function: Count the running time of the index function. What should I do ??

The index function is modified as follows:

Run the program. The execution result is as follows:

welcome to index page
cost time: 2.000999927520752

We can see that adding new functions to the index function is indeed implemented, but it violates the open and closed principle.

If you want to add a new function for the index function, you need to use the decorator.

Modify code

Run the program and view the execution result

welcome to index page
run time: 1.0

The execution result shows that the running time of the index function has been counted.

However, you can see from the source code that the source code of the index function has not been modified, but the method of calling the index has been modified.

Another problem is that timmer can only be used to decorate the index function. If you want to calculate the running time of other functions in the future, you have to redefine other decorators, this is too inflexible.

Modify the code above

Run the program and view the program execution result.

welcome to index page
run time: 4.0

As you can see, the source code of the index function is not modified, and the method of calling the index function is not changed. However, the time statistics function is still added to the index function. Here, the decorator is used.

To analyze the execution process of the above Code:

This is the execution process of the index function of the decorator.

3. Simplified use of decorator

Now I have another function home. Now I want to calculate the running time of the home function. You can modify the Code as follows:

Run the program. The execution result is as follows:

welcome to index pagerun time: 3.0
welcome to home pagerun time: 4.0

As you can see, every time you call timmer, which counts the running time of the program, you must first pass the called function name as a parameter to the timmer.

Then, assign the execution result of the timmer decorator to the called function name, and finally call the decorated function. Is it too troublesome ??

In fact, the decorator in python can be simplified to the following format:

Program Execution result

welcome to index pagerun time: 2.0
welcome to home pagerun time: 4.0

We can see that@ Add the modifier name to the top of the decorated objectYou can also add the features defined in the annotator to a function.

4. Definitions and calls of multiple decorators

In the preceding example, timmer,

If you want to add a user authentication function for the index function, you can define a decorator named auth.

Run the program

The execution result shows that the decorator auth for user login password verification has been defined and called successfully.

If you want to add the user authentication function for the index function and calculate the execution time of the index function, how can you call it when you use the decorator?

In the code above, I added two decorators to the index function. Now there is a question: Which one is called first and which one is called later ??

To analyze,

If the timmer decorator is called first, the program executes the timmer decorator first, and then executes the auth decorator, prompting you to enter the user name and password,
In this way, the statistical time of timmer will include the time for entering the user name and password, which will be much more than two seconds after the index function sleeps;
If the auth decorator is called first and the timmer decorator is called later, the running time of the timmer modifier statistics should only include the execution time value of the index function, which should be within the time range of more than 2 seconds.

Run the program. first enter the wrong user name and password to extend the execution time of the program.

From the execution result of the program, we can know that the program runs the timmer decorator first and then the auth decorator. Therefore, the time for timmer statistics includes the user authentication time, therefore, the running time measured by timmer is much longer than 2 seconds after index sleep.

So here is a conclusion:

When a function is decorated by two decorators at the same time, add the top decorator of the function to execute it first, and add the decorator below to decorate it first.

Change the positions of the timmer and auth decorators in the above example

 

Run the index function and enter the wrong username and password to increase the user authentication time.

We can see that the time measured by timmer only includes the running time of the index function, and does not include the time when the user authenticates.

In the above example, the index function is decorated by the Code decoration process of the timmer and auth decorators.

In the above conclusion, when a function is simultaneously decorated by two decorator, the decorator added below is decorated first.

1. the original index of the timmer modifier can be written as: index = timmer (index) 2. in the timmer decorator, The timmer decorator actually returns the inner memory address. So here, after the index = inner3.timmer decorator is completed, it is decorated by the auth decorator, in this case, you can write index = auth (index), 4. here, the index in auth brackets is no longer the original index function, but the index that has been decorated by timmer, so index = auth (timmer (index) 5. because the result of timmer decoration is equal to the memory address of the inner function, the index = auth (inner)

Now, the decoration process of the two decorators is known. Let's look at the execution process of the program.

Therefore, the time for the user to enter the user name and password is not counted by the timmer decorator.

5. Set and define parameters of decorated Functions

Let's take a look at a piece of code.

As shown above, the home function adds a parameter, and the index function does not have a parameter.

According to the definition and call method of the normal function, the method for calling the index function and the home function should be as follows:

index()home("python")

Then we run the program and we will find that the program throws an exception.

An exception indicates that the inner function does not require a location parameter, but we provide a location parameter.

Return to the part defined by the timmer decorator. We can see that the internal function of the timmer decorator does not have any defined parameters.

In this way, the timmer modifier can only be used to decorate functions without parameters,

We can add a parameter to the inner function when the timmer modifier is defined.

In this case, the timmer modifier will throw an exception when decorating the index function, because the index function has no parameters.

File "E:\python_learn\py_code\test.py", line 27, in <module>index()
TypeError: inner() missing 1 required positional argument: 'name'

When the number of parameters of the decorated function is unknown, that is, the parameter length of the decorated function is variable and the format is not fixed,

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.