Python base day-7[closures, adorners]

Source: Internet
Author: User
Tags closure

Closures:

First of all, what is a closure package?

A closure is a function defined inside a function that contains a reference to an outer scope, but does not contain a global scope. Since the scope of the function is fixed dead at the time of definition , the closure function has the characteristics of its own scope and delay calculation.

Closure function Definition: If an intrinsic function contains a reference to an outer scope, it does not contain a global scope. Then this function is considered a closure function. The closure function can use ". __closure__" To view the properties of the closure function. Let's look at an example:

def t ():     = +    def  s ():        print(money)    return s            # returns the function s, not a value that the function has performed  = t () C ()print(c.__closure__)   #查看属性执行结果: D:\Python\Python36 -32\python.exe e:/python/day-7/day7_ notes. Py(<cell at 0x00a4c3d0:int object at 0x60625d20>,) Process finished with exit code 0

The function S is the intrinsic function defined in the function t

The function s refers to an external variable money, but is not a global variable. The function s is a closure function.

Adorner:

An adorner can be any callable object, or an object that is decorated can be any callable object.

Adorner function:

Adds a new feature to a decorated object without modifying its source code and the way it is called.

The syntax of the adorner:

A separate line above the adorned object, @ the adorner name. The function name immediately below is called to the adorner, and the function name is returned to it after processing.

Multiple adorners: Who is on top who first executes, who is below who first calculates.

Example:

ImportTime #导入模块ImportRandomdefTimmer (func): #装饰器模块defwrapper (): #定义一个闭包函数wrapper stime=time.time () #闭包函数内 calculates the sleep time of index, here is the start calculation of the func () #执行index的函数内容 stptime=time.time () #index的函数执行完毕后的停止时间Print('run time is%s'% (stptime-stime)) #打印运行了多久returnwrapper ()defindex (): #定义函数index time.sleep (Random.randrange (The) ) #函数内执行睡一定时间, and then print the Welcome messagePrint('welecome to index page') Index=Timmer (Index) #调用装饰器运行结果: D:\Python\Python36-32\python.exe e:/python/day-7/tmp.pywelecome to index Pagerun time is1.0000858306884766Process finished with exit code 0

This is the simplest example of an adorner. What if we still have to pass the parameter, so that the user can not feel the adorner? Let's look at the following.

Example:

Import TimeImportRandom#Decorative DevicedefTimmer (func):defWrapper (*args,**Kwargs): #接受可变长参数 start_time=time.time () Res=func (*args,**Kwargs) Returns the return value of the #接收保存对应函数 stop_time=time.time ()Print('run time is%s'% (stop_time-start_time)) returnThe return value of the Res #执行完毕 return functionreturnwrapper#be decorated function@timmer #使用 @ mode call Adornerdefindex (): 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)return123123123123123123123123123123123123123123 #return has a return valueindex () #调用 no parameter passed inPrint(Home ('ABC') ) #调用传入参数 ' abc ' execution result: D:\Python\Python36-32\python.exe e:/python/day-7/tmp.pywelecome to index Pagerun time is2.0000545978546143welecome to ABC HOME pagerun time is2.0000154972076416123123123123123123123123123123123123123123Process finished with exit code 0

Python base day-7[closures, adorners]

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.