Python Learning note 7 (decorator)

Source: Internet
Author: User
Tags closure

Closed Package (closure) is an important grammatical structure of functional programming.

Definition: If a reference is made to a variable in an external scope (but not at the global scope) in an intrinsic function, then the intrinsic function is considered a closure (closure).

def outer ():                                    = 1                                        def  Inner ():                                               Print(x)                                         return  inner                               = outer ()                                f ()                  

Inner is an intrinsic function, and inner refers to the outer scope of the variable x (x in the outer scope outer, not the global scope), then this intrinsic function inner is a closure.

closure = function Block + environment when defining functions , Inner is the function block, and X is the environment.

Decorative Device

An adorner is essentially a function that handles other functions that allow additional functions to be added without the need to modify the code, and the return value of the adorner is also a function object.

It is often used in scenarios where there is a need for facets, such as insert logs, performance testing, transaction processing, caching, and permission validation. Adorners are a great design for solving such problems, and with adorners, we can pull out a lot of similar code that is not related to the function itself and continue to reuse it. In summary, the function of an adorner is to add additional functionality to an already existing object .

Simple Adorner function:

The @ symbol is the syntactic sugar of the adorner, which is used when defining a function to avoid another assignment

Import TimedefShoe_time (f):definner (): Start=Time.time () f () End=time.time ()Print(end-start)returnInner@shoe_time#foo = shoe_time (foo)deffoo ():#start = Time.time ()    Print("foo ...") Time.sleep (2)    #end = Time.time ()    #print (End-start) #2.0001144409179688#foo ()@shoe_time#bar = shoe_time (bar)defBar ():#start = Time.time ()    Print("Bar ...") Time.sleep (3)    #end = Time.time ()    #print (End-start) #3.001171588897705#Bar ()#shoe_time (foo) #2.0001142024993896#Shoe_time (BAR) #3.001171588897705Foo ()#foo ... # 2.0001144409179688Bar ()#Bar ...                          #3.00017142295837

Decorated function with parameters
#function function plus parameterImport TimedefShoe_time (f):definner (x, y): Start=Time.time () f (x, y) end=time.time ()Print(end-start)returnInner@shoe_timedefAdd (A, b):Print(A +b) Time.sleep (3)#@shoe_time#def foo ():#print ("foo ...")#Time.sleep (2)#@shoe_time#def Bar ():#print ("Bar ...")#Time.sleep (3)#Add (1,3)#4               #3.000171661376953#Indefinite length parameterImport TimedefShoe_time (f):defInner (*x,**y): Start=Time.time () F (*x,**y) End=time.time ()Print(end-start)returnInner@shoe_timedefAdd (*a,**b): Sum=0 forIinchA:sum+=IPrint(sum) time.sleep (3)#@shoe_time#def foo ():#print ("foo ...")#Time.sleep (2)#@shoe_time#def Bar ():#print ("Bar ...")#Time.sleep (3)#Add (1,3,4,6,78)# the                             #3.000171661376953
Adorner with parameters

The adorner also has greater flexibility, such as an adorner with parameters: in the above adorner call, such as @shoe_time, the adorner's only parameter is the function that executes the business. The adorner syntax allows us to provide other parameters, such as @decorator (a), when called. This provides greater flexibility for the authoring and use of adorners.

#Adorner with ParametersImport TimedefLogger (flag=""):    defShoe_time (f):defInner (*x,**y): Start=Time.time () F (*x,**y) End=time.time ()Print(end-start)ifFlag = ="true": With open ("Log Records","a", encoding="UTF8") as G:g.write ("The value is:%s time is:%s\n"% (f (*x), (end-start))) returnInnerreturnShoe_time@logger ("true")#@show_timedefAdd (*a,**b): Sum=0 forIinchA:sum+=IPrint(Sum) time.sleep (3)    returnSum@logger ("ABC")deffoo ():Print("foo ...") Time.sleep (2)#@shoe_time#def Bar ():#print ("Bar ...")#Time.sleep (3)Add (1,3,4,6,78)# the                    #3.000171661376953Foo ()

@logger ("true") has done two things:

(1) @ogger ("true"): Gets the closure function show_time, which holds the environment variable flag

(2) @time: Add=show_time (ADD)

The logger above is an adorner that allows parameters. It actually encapsulates a function of the original adorner and returns an adorner (a closure function that contains parameters). When we call with @logger ("true"), Python can discover this layer of encapsulation and pass parameters to the adorner's environment.

Python Learning note 7 (decorator)

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.