Python Basics (7) Closure function, adorner

Source: Internet
Author: User
Tags wrapper

One, closure function closure function: 1, function inside the definition function, become an internal function, 2, change the internal function to include the external scope, rather than the global role of the domain name Word reference then the inner function becomes the closure function
#the simplest non-parametric closed-packet functiondeffunc1 () name='Ares'    defFunc2 ()Print(name)#closure function with parameter and return valuedefTimmer (func):defWrapper (*args,**Kwargs): Start_time=time.time () Res=func (*args,**Kwargs) Stop_time=time.time ()Print('run time is%s'% (stop_time-start_time)) returnResreturnWrapper
Second, higher order function 1) The function receives the parameter is a function name 2) The return value of the function is a function name 3) satisfies any one of the above conditions, can be called higher order function
#High- Order function Application 1: Passing functions as parameters to higher-order functionsImport Timedeffoo ():Print('From the foo')defTimmer (func): Start_time=time.time () func () Stop_time=time.time ()Print('function%s Run time is%s'% (func,stop_time-start_time)) Timmer (foo)#Summary: We did add the Foo runtime function to the function foo, but Foo was originally executed in Foo (), and now we need to call the higher-order function Timmer (foo), changing the way the function is called#High -Order function Application 2: The function name as a parameter to the higher-order function, the higher-order function directly return functions of the nameImport Timedeffoo ():Print('From the foo')defTimmer (func): Start_time=time.time ()returnfunc stop_time=time.time ()Print('function%s Run time is%s'% (func,stop_time-start_time)) Foo=Timmer (foo) foo ()#Summary: We did not change the way Foo was invoked, but we did not add any new features to Foo
Summary of higher order functions1. The parameter received by the function is a functional namefunction : Add a new function to the function without modifying the source code of the function .Insufficient: Changes the way the function is called2. The return value of a function is a functional nameFunction : Does not modify the function's Calling methodInsufficient: Cannot add new features Three, function nesting
#nested definitions of functionsdefF1 ():defF2 ():deff3 ():Print('From f3')        Print('From F2') F3 ()Print('From F1') F2 ()#Print (F1)F1 ()" "From F1from f2from f3" "
four, decorative device1. Definition:The function is the devicedecoration is cosmetic, meaning to add new functions for other functionsAdorner definition: The essence is the function, function is to add new functions for other functions2, the adorner follows the principle: open Closed principle (open to the extension, the source code modification is closed)i.e., 1) do not modify the source code of the decorated function2) After adding a new function to the decorated function, the calling method of the decorated function is not modified3, adorner, the essence of the adorner can be any callable object, the decorated object can also be any callable object,The function of the adorner is to add new features without modifying the source code of the object being decorated and the method of calling it.  adorner = higher order function + function nesting + closure Basic Framework
# This is one of the most basic shelves to implement an adorner. def  defreturn Wrapper

An adorner that counts a function run time

#Import Time#Import Random##装饰器#def Timmer (func):## Func=index#def wrapper ():#start_time = Time.time ()#func () #index ()#stop_time=time.time ()#print (' Run time is%s '% (stop_time-start_time))#return wrapper##被装饰函数#def index ():#Time.sleep (Random.randrange (1,5))#print (' Welecome to index page ')##def Home ():#Time.sleep (Random.randrange (1,3))#print (' Welecome to HOME page ')##Index=timmer (Index) #index =wrapper#Home=timmer (Home)##index () #wrapper ()#Home ()

Adorner syntax: A separate line above the adorned object, @ Adorner name, # @timer is equivalent to Index=timmer (index)

Import TimeImportRandom#Decorative DevicedefTimmer (func):defwrapper (): Start_time=time.time () func () Stop_time=time.time ()Print('run time is%s'% (stop_time-start_time)) returnwrapper#be decorated function@timmer#Index=timmer (Index)defindex (): Time.sleep (Random.randrange (1,5))    Print('welecome to index page')#@timmer #home =timmer (home)#def Home ():#Time.sleep (Random.randrange (1,3))#print (' Welecome to HOME page ')Index ()#wrapper ()#Home ()

Add more adorners:

#add more adornersImport TimeImportRandom#Decorative DevicedefTimmer (func):defwrapper (): Start_time=time.time () func () Stop_time=time.time ()Print('run time is%s'% (stop_time-start_time)) returnwrapperdefAuth (func):defdeco (): Name=input ('Name:') Password=input ('Password:')        ifName = ='Egon'  andPassword = ='123':            Print('Login Successful') func ()#wrapper ()        Else:            Print('Login Err')    returndeco##多个装饰函数 by the decorated function, added from top to bottom@auth#Index=auth (wrapper) #index =deco #index =auth (wrapper) #index =deco@timmer#Index=timmer (Index) #index =wrapperdefindex ():#Time.sleep (Random.randrange (1,5))Time.sleep (3)    Print('welecome to index page')defHome (): Time.sleep (Random.randrange (1,3))    Print('welecome to HOME page')#index () #deco ()#Home ()

Decorator Revision:

#Decorator RevisionImport TimeImportRandom#Decorative DevicedefTimmer (func):defWrapper (*args,**Kwargs): Start_time=time.time () Res=func (*args,**kwargs)#Receive ParametersStop_time=time.time ()Print('run time is%s'% (stop_time-start_time)) returnRes#Increase return value    returnwrapper#be decorated function@timmerdefindex (): Time.sleep (Random.randrange (1,5))    Print('welecome to index page') @timmerdefHome (name): Time.sleep (Random.randrange (1,3))    Print('welecome to%s HOME page'%name)return123123123123123123123123123123123123123123index () res1=index ()Print('Index return%s'%res1) Res2=home ('Egon')#Wraper ()Print('Home Return%s'%RES2)

Python Basics (7) Closure function, adorner

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.