5. Python Adorner High-order function + closure + function nesting = Adorner

Source: Internet
Author: User
Tags closure

A. What is an adorner?

The decorator is actually a function that can provide additional functionality to other Functions.

The adorner does not modify the source code of the original function when it adds functionality to other functions, and does not modify the way the original function is Called.

Higher order function + function nesting + closure = Adorner


1.1 What is a higher order function?

The 1.1.1 function receives a parameter that includes a function name.

The return value of the 1.1.2 function is a function name.

In fact, these two conditions are very good to meet, the following is an example of a higher-order Function.

def test1 ():

Print "hamasaki ayumi"

def test2 (func):

return test1

The following code satisfies all the conditions of the higher order function,

1.1.3 any condition that satisfies the above conditions can be called higher order Functions.

If we just add a function to a function and do not modify the code of the original function, we can implement it through the higher order function, and the following is the function of adding a calculation execution time to the function and not modifying the original function Code.

#!/usr/bin/python2.7

#-*-coding:utf-8-*-

Import time

def Foo ():

Time.sleep (1)

Print "hamasaki Ayumi <<a best>> 3.28 now on sale!"

def Test (func):

Start_time = Time.time ()

Func ()

Stop_time = Time.time ()

Run_time = Stop_time-start_time

Print Run_time


Test (foo)


Output result:

Hamasaki Ayumi <<a best>> 3.28 now on sale!

1.00331807137


From the above test results, it can be seen that the original code of the Foo function is not modified, and the function is added a function to show the execution Time.

Although Higher-order functions are used to add functionality to the original function foo, the invocation of the original function is modified to violate the open closure Principle.


Just said that the parameter received by the higher order function is a function name, and we can use this feature to add functionality to the function (without modifying the original code).

then, Another feature of the Higher-order function, The return value is a function, if you apply this feature, you can do not change the way the function is Called. Let's try it out, just through the High-order function, whether the adorner function can be accomplished.

Import time

DEF runtime (func):

Start_time = Time.time ()

Func ()

Stop_time = Time.time ()

Run_time = Stop_time-start_time

Print Run_time

return func


def Foo ():

Time.sleep (1)

Print "hamasaki Ayumi <<a best>> 3.28 now on sale!"

Foo = runtime (foo)

Foo ()

The output results are as follows:

Hamasaki Ayumi <<a best>> 3.28 now on sale!

1.0050868988

Hamasaki Ayumi <<a best>> 3.28 now on sale!


From the results obtained, the Foo function was executed more than once, for specific reasons, to Analyze.

First called runtime (foo), the interpreter explained to Func (), the Foo function was executed once, the runtime function in return, the Foo function body, return to the Foo variable, and finally we call Foo (), The Foo function has been executed more than once, which is obviously not the effect we want.

so, the function that the "adorner" possesses, only through the High-order function, is impossible to Realize.

next, we need to use the remaining two points of knowledge, namely function nesting and function closure.


2. What is function nesting?

When it comes to function nesting, there is always a thought that calling another function in a function is a function nesting, as in the following Example.

DEF F1 ():

print ' F1 '

def F2 ():

print ' F2 '

F1 ()

Attention!! This is not a nested function!!

A true function nesting means that a function is defined in a Function.

DEF F1 ():

print ' F1 '

def F2 ():

print ' F2 '

Print Locals ()

F1 ()


Like this, a function is created in the body of a function, and this form belongs to the function nesting.


3. What is a closure function?

The closure function, presumably, can be interpreted as, in an intrinsic function, to an outer scope (where the outer scope refers to the global scope!). ), the inside of the function can be understood to be a closure, the following is an example of a closure Function.

A = 1

DEF F1 ():

A = 2

def F2 ():

Print a

F2 ()

F1 ()


3.1 Some usage considerations for closure Functions.

3.1.1 The first thing to pay attention to is! Inside the closure function, the default is not to modify the external scope of the variable!! (use the nonlocal keyword to declare EXCEPTIONS)

Example 1:

DEF F1 ():

x = 1

def F2 ():

x = 2

Print X

Print X

F2 ()

Print X

F1 ()

The result of the final output is:

1

2

1

The x variable defined in the closure function does not affect the x variable of the outer scope.


Example 2:

def Foo ():

A = 1

def Bar ():

A = a + 1

Return a

Return bar

f = Foo ()

Print F ()

Analyze the problem with this code, when executing the foo () function, python will pour the closure function bar to analyze the local variables of this scope, in fact, Python internally stipulates that the variable on the left side of the equal sign is a local variable, and in the closure function bar, A is assigned to the left side of the equal sign, It is assumed by Python that this A is a local variable in the closure function bar, and when the program runs to a=a+1 when it executes print F (), python will find the value of a in the closure function bar at the right of the equal sign, and if not, it will be an Error. (because Python has previously treated a as a local variable in the bar closure function.) )


So next, let's combine the three points of the High-order function + closure + function nesting to see if we can implement the Adorner's Function.

#!/usr/bin/python2.7

#-*-coding:utf-8-*-

Import time

DEF runtime (func):

def func_in ():

Start_time = Time.time ()

Func ()

Stop_time = Time.time ()

Run_time = Stop_time-start_time

Print Run_time

Return func_in

def Foo ():

Time.sleep (1)

Print "hamasaki Ayumi <<a best>> 3.28 now on sale!"

Foo = runtime (foo)

Foo ()


Results of the Output:

Hamasaki Ayumi <<a best>> 3.28 now on sale!

1.00491380692


As can be seen from the results, this time through the above mentioned three knowledge points, the success of the initial implementation of the "adorner" Function.

Although this function is closed by functions, nested functions, High-order functions, The characteristics of the three functions of the function of a similar adorner, but there is a small flaw, we look at the last two lines of the previous example of the Code.

Foo = runtime (foo)

Foo ()

If there are many functions to use the previous "adorner", each function must be re-assigned before the call is particularly troublesome!

In order to achieve a more perfect function of the adorner, you also need to introduce the "syntax sugar" in python, which is an @ Symbol.

The "@" symbol is the syntax sugar of the Python adorner, using the name of the adorner after the @, and the adorner, "decorate" which function, add the adorner to the top of the Function. The following is an example of the use of the adorner syntax sugar.

DEF runtime (func):

def func_in ():

Start_time = Time.time ()

Func ()

Stop_time = Time.time ()

Run_time = Stop_time-start_time

Print Run_time

Return func_in


@runtime

def Foo ():

Time.sleep (1)

Print "hamasaki Ayumi <<a best>> 3.28 now on sale!"


Foo ()


# Use the Rumtime adorner to "decorate" the Foo Function.

@runtime = foo = Runtime (foo)

The two syntactic meanings are the same, except that you don't have to re-assign the function before each call to the Function.


This article is just a preliminary understanding of the adorner! More about the adorner is in the following article ~ to be Continued ~



This article is from the "rebirth" blog, make sure to keep this source http://suhaozhi.blog.51cto.com/7272298/1909347

5. Python Adorner High-order function + closure + function nesting = Adorner

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.