Python Basics-Day 4 learning Note-decorator Decorator

Source: Internet
Author: User
Tags closure ldap wrapper python decorator

    • Knowledge Preparation for adorners
    • Functions, Function arguments
    • Scope: global variable, local variable
    • variable parsing rules : LEGB-assuming nested functions (second-level functions), the parser looks for variables in the inner function in the following order. A variable that meets the requirements is first found on any layer and is no longer looked out. If not, then throw n
      1. Local-native function, which is assigned in any way, and is not declared as a global variable by the global keyword
      2. Enclosing-The local scope of the outer space of the intrinsic function directly (that is, its upper function). Multi-layered nesting, there is a layer-by-level look-up until the outermost function
      3. Global-Universal space (module enclosed.py), variable assigned at the top level
      4. Buildin-Find variables in the predefined variable names in the built-in module (__BUILDIN__).
    • Variable lifetime: The lifetime of a local variable exists as a function is called and dies as the function ends.
    • nested functions : function in a set of functions and called.
    • Higher order function : one function accepts another function as a variable. function is variable
    • all objects in Python (objects, and then the problem with object programming). When a function is defined, the function is the first class object/class object. The so-called first class object, which means that an object can be named with an identifier, and the object can be treated as data. For example, an assignment, passed as a parameter to a function, or as a return value return.
    • function objects vs. function calls (very easy to confuse)
def func ():     return " Hello,world "  = func   #Ref2 = func ()  #  function call, type (REF2) is string
    • closures: an adorner is actually a closure, taking a function as an argument and returning an alternative function. So it's important to understand the closure concept. The so-called closures are the objects that are obtained when the statements that compose the function are packaged together with the execution Environment of these statements. Summarize:
      • The most important use value of closures: the context of the execution of the storage function;
      • Closures are found in the execution environment in which they are captured (the context in which the DEF statements are fast), and are followed by LEGB rules, until they meet the required variables, or throw exceptions
Decorator Concept:

definition : The "Device" of the adorner is a function, the basic syntax is defined by DEF, the essence is the function, its function is to decorate other functions, add additional functions for other functions

principle : adorners are completely transparent to the decorated function

    1. You can modify the source code of the decorated function.
    2. Cannot modify the calling method of the decorated function

structure : Higher order function + nested function;

    1. function is "variable"
    2. Higher order functions
      1. Passing a function name as an argument to another function------add functionality to it without modifying the source code of the decorated function
      2. The return value contains the function name-----does not modify the function's Calling method
    3. Nested functions

In summary, an adorner is a high-order function that returns a function with at least one function nested (returned as a return value)

How it works : func = Deco (func) With syntax sugar syntax Suger to denote @

The first step: the decorated function is passed as a parameter to the adorner function, and the adorner function is executed, and the return value is recorded as Newfunc

Step Two: The original function re-assigns the value to Newfunc

Classroom examples-How to build adorners
    • simplest adorner : Moduel 2-vedio 7-Small climax of the adorner.
1 #!user/bin/env python2 #-*-coding:utf-8-*-3 4 Import Time5 6 7 defTimer (func):#timer (test1), passing Test1 's memory address to Func, and finally returning to Deco's memory address by return8     defdeco ():9Start_time =time.time ()Ten func () OneStop_time =time.time () A         Print('The func run time is%s'% (stop_time-start_time)) -     returnDeco#directly returns the memory address of the Deco function, so the following test1 = Deco (test1), so test1 () can be called normally -  the  -@timer#is one step to run the work, equals test1 = Timer (test1) Note here can not be parentheses, because the decoration of the function, and test1 () is a return value - deftest1 (): -Time.sleep (3) +     Print('In the test1') -  +  ATest1 ()#at this point the test1 executes the Deco memory address, because return Deco in the timer function at Print(test1)#the memory address of the decorated test1 is returned: <function Timer.<locals>.deco at 0x00000244d3824048>
View Code

Logical interpretation

Start line End Line Code Explain
- 4 Import time Importing the time module
4 7 def timer (func) Timer (test1), test1 memory address into Func, final return deco memory address
7 16 @timer

Jump directly to the grammar sugar and execute the timer decorator

means: Test1 = timer (test1)

16 8 Def deco ()  
8 13 Return deco The return value is the memory address of Deco
13 22 Test1 () Call Test1 (), @timer re-assignment, at which time the Deco memory address is executed, and finally the Deco () is called
22 9 Start_time = Time.time () Executive Deco ()
9 10 Func () Inside the Deco function, the variable func begins to be called, at which point Func is test1 (),
10 18 Time.sleep (3) Perform the original test1 ()
18 19 Print (' in the Test1)
19 11 Stop_time = Time.time ()
11 12 Print (' Run time =%s '% (stop_time-start_time)

The core is the transfer of memory addresses.

    • the decorated function with parameters :
#!user/bin/env python#-*-coding:utf-8-*-Import TimedefTimer (func):#Pass the memory address of the Test2 to Func    defDeco (*args,**kwargs):#*args with a non-fixed parameter, **kwargs; a decorated function that satisfies parameters and has no parameters .Start_time =time.time () func (*args,**Kwargs) Stop_time=time.time ()Print('The func run time is%s'% (stop_time-start_time)) returnDeco#returns the memory address of the Deco function directly@timer#test2 = Timer (test2) = Deco; Test2 () = Deco (); So when test2 has a function variable, Deco also needs to add a function variable. defTest2 (name):#test2 itself with parametersTime.sleep (3)    Print('In the test2') Test2 ('Alex')
View Code

In this case,

      1. The function deco () which corresponds to the memory address of the final swap in the adorner should also have a function when the decorated function test2 its own parameters.
      2. Because the adorner ends up being used for different decorated functions, the parameters of Deco () are applied to *args and **kwargs of non-fixed parameters.
    • the decorated function has a return value : Because home () = wrapper (home), the last decorated home () returns a call to the wrapper memory address. The return data of the original function is also written in wrapper.
1 #!user/bin/env python2 #-*-coding:utf-8-*-3 4USER,PASSWD ='Alex','abc123'5 6 defAuth (func):7     defWrapper (*args,**Kwargs):8Username = input ('Username'). Strip ()9Password = input ('Password'). Strip ()Ten  One         ifuser = = Username andpasswd = =Password: A             Print("\033[32;1muser has passed authorization\033[0m") -res = func (*args,**kwargs)#Assign Value -             returnRes#Return to Res the         Else: -Exit'\033[31;1minvalid username or password\033[0m') -     returnWrapper#returns the memory address of the wrapper -  +@auth (auth_type="Local") - defHome (): +     Print('Welcome to Home Page') A     return "From home" at  - Print(Home ())#print back from home
View Code
    • Adorner with parameters (final adorner): If the adorner has parameters, the decorated function has parameters, then the adorner will have three layers.
1 #!user/bin/env python2 #-*-coding:utf-8-*-3 4 #example three: Adorner with parameters (end adorner)5 #Scenario requirements: With a variety of authentication methods. Home () authentication method with local locally authentication, BBS () with remote LDAP6 7USER,PASSWD ='Alex','abc123'8 9 Ten defAuth (auth_type):#Home () of Can One     defOuter_wrapper (func): A         defWrapper (*args,**Kwargs): -Username = input ('Username'). Strip () -Password = input ('Password'). Strip () the  -             ifuser = = Username andpasswd = =Password: -                 Print("\033[32;1muser has passed authorization\033[0m") -res = func (*args,**kwargs)#Assign Value +                 returnRes#Return to Res -             Else: +Exit'\033[31;1minvalid username or password\033[0m') A         returnWrapper#returns the memory address of the wrapper at     returnOuter_wrapper -  - defindex (): -     Print('Welcome to Index page') -  -  in@auth (auth_type="Local") - defHome (): to     Print('Welcome to Home Page') +     return "From home" -  the Home () *  $@auth (auth_type="LDAP")Panax Notoginseng defBBS (): -     Print('Welcome to BBS page') the  +BBS ()
View Code
Reference:

"Why can a function in Python return a function defined inside a function?" ", https://www.zhihu.com/question/25950466/answer/31731502

"12-Step Easy python decorator", http://python.jobbole.com/81683/

Python Basics-Day 4 learning Note-decorator Decorator

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.