Python Learning Note 7: adorners

Source: Internet
Author: User

First, what is an adorner

Adorner, which is itself a function.

The function of the adorner is to add some functionality to the existing function without changing its invocation mode, which is generally common.

It is often used in scenarios where there is a need for facets, such as inserting logs, performance testing, transaction processing, caching, permission checking, and so on. (This quote: https://zhuanlan.zhihu.com/p/25648515)

Second, the prerequisite knowledge of learning decorators

1. function is variable

2. High-order function

3. Function nesting

Above three knowledge points, in my previous blog ' Python study note 6: function ' in detail, here do not repeat

A city example

1, Scene: Write a system with Python, the project has been online, now found that the system performance is very poor, want to write a program to count the running time of each function.

2, assume that the system has hundreds of functions, the following is one of them:

    

3, now write a function to count its running time, you can write:

  

4, if the method according to 3, when there are many many functions in the system, it is necessary to call a timer function to count the running time of the function, so it is time-consuming.

What to do, then introduced the adorner: the timer function is actually a common program, for each function in the system need it to count the running time.

In this case, we can put such a common function, inline definition in the function timer, the Deco function body is the same as in 3:

  

  

5, if we want to define the function to use the adorner, in order to avoid the Run = Timer (run) Such an assignment statement, to use the adorner's syntax sugar @, so that the code is more concise and tall!

The complete code is as follows:

  

The operating result is:

      

  

  

  

  

Python Learning Note 7: adorners

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.