Python self-taught music-an introduction to decorators

Source: Internet
Author: User

Before I learned a bit about object-oriented knowledge, I felt that there was a correlation, for example, the first element of the adorner was the closure of the decorated function, not the change, and the second was the extensibility of the OJ body of the adorner.

Adorner essentials: higher-order functions + nested functions = adorners

Knowledge points to be mastered: 1, function as variable

2. Higher-order functions (function parameters are also functions)

3. Nested functions

Adorner one: The adorner does not have parameters, the function is decorated without parameters

Simple requirements: Existing two simple print content functions, now need to count each function run time without changing the two function source code

Import time
def timer (func): #用到高阶函数
Def deco (): #用到函数嵌套
Start_time = Time.time ()
Func ()
Stop_time = Time.time ()
Print ("The Func Run%s"% (Stop_time-start_time))
Return deco
@timer
def test1 ():
Time.sleep (3)
Print ("I am test1")
@timer
Def test2 ():
Time.sleep (3)
Print ("I am test2")
Test1 ()
Test2 ()
Execution order: First, the program from the top down, go to the definition of the timer function will jump to @timer place, detected that the timer is used as an adorner, the system will go to search where to use the timer as the adorner, after the completion of the search, the execution of the timer, and then execute the test1 we call (), because test1 is decorated by a timer, so the adorner is executed first, and when it executes to func () inside the adorner, then Func () is test1 ()! Test2 () is the same
The effect of the adorner is: there is no change in the original function of the source code and function call mode, but also to add new functions to the function

Adorner two: decorated function with parameters
Adorner three: The decorated function has a return value
Decorator Four: The adorner itself with parameters



Python self-taught music-an introduction to decorators

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.