Python function (3): Adorner

Source: Internet
Author: User

yesterday, I learned a lot about the concepts and knowledge of function, which has a function of closure. Many people are not very clear about the role of closures, today we come to know a new point of knowledge decorator. It is a classic application of the closure Function.

Preview:

Write adorners, add authentication function to multiple functions (user's account password originates from file), require login success once, subsequent functions no longer need to enter user name and password

first, Wedge

def func1 ():     Print ('infunc1')

To calculate the execution time of the above function:

Import  time def func1 ():     = time.time ()    print('infunc1')    =Print 
Func1 ()

But if you want to calculate the execution time of all the functions you have written, you should change the Code. Write a function:

 import   time  def   timer (func): start  = time.time () func () print  (time.time ()- start)  def   func1 ():  print  ( '   )  def   Func2 ():  print  ( in func2   '   ' timer (func1) timer (func2)  

No matter how many functions we write, we can call this timing function to calculate the execution time of the function ... Although the cost of the modification is now small and small, it has changed the way the function is called, if there are many functions to change a lot

All you have to do is let your coworkers still call func1, but the effect of calling the timer method can be Achieved.

Import  time def Timer (func):     = time.time ()    func    ()print(time.time ()- start)def  func1 ():     Print ('infunc1'=timer (func1)  # Error func1 ()

unfortunately, The above code will be error, because the timer method needs to pass a Func parameter, we can not pass the argument when the assignment, because as long as the execution of func1 = Timer (func1), The timer method is executed directly, the following sentence func1 there is no meaning.

second, the formation of the decorative device

The function is the device

Decoration is cosmetic, meaning to add new functions for other functions

Adorner definition: The essence is the function, function is to add new functions for other functions

Import  time def func1 ():     Print ('infunc1') def Timer (func):     def Inner ():         = time.time ()        func ()print(time.time ()- start)    return  = timer (func1) func1 ()
adorner-simple version 1

Now the only trouble is to make an assignment call ... Python developers also feel an eyesore, so they provide us with a syntactic sugar to solve this problem!

 import   time  def   timer (func):  def          inner (): start  = time.time () func ()  print  (time.time ()- start)  return   Inner@timer  #  ==> func1 = Timer (func1)  def   func1 ():  print  ( "  In func1    ) func1 ()  
Decorator--grammar Sugar

here, we can summarize briefly:

The essence of an adorner: a closure function

The function of the adorner: the function of the original function is extended without modifying the original function and its calling mode

The last problem to solve, just we discussed the adorner is decorated without parameters of the function, now to decorate a function with parameters what to do

def Timer (func):     def Inner (a):         = time.time ()        func (a)        print(time.time ()- start)    return  Inner@timerdef  func1 (a):    print(a) func1 (1)
Adorner--an Adorner with parameters

If you have two functions, you need to pass the arguments differently.

Import timedefTimer (func):defInner (*args,**kwargs): Start=Time.time () re= Func (*args,**Kwargs)Print(time.time ()-start)returnRereturnInner@timer#==> func1 = Timer (func1)deffunc1 (a, b):Print('in func1') @timer#==> func2 = Timer (func2)defFunc2 (a):Print('in Func2 and get a:%s'%(a))return 'fun2 over'Func1 ('aaaaaa','bbbbbb')Print(FUNC2 ('aaaaaa'))
adorner-universal Decorator

If you have a function that has a return value

Import timedefTimer (func):defInner (*args,**kwargs): Start=Time.time () re= Func (*args,**Kwargs)Print(time.time ()-start)returnRereturnInner@timer#==> func2 = Timer (func2)defFunc2 (a):Print('in Func2 and get a:%s'%(a))return 'fun2 over'Func2 ('aaaaaa','bbbbbb')Print(FUNC2 ('aaaaaa'))
Adorner-adorner with return value

Iii. the principle of open closure

1, the expansion is open

We say that no one program can have all the features in mind at the beginning of the design and will not make any updates or changes in the Future. So we have to allow Code extensions, add new Features.

2, the modification is closed

As we have just mentioned, as we write a function that is likely to have been delivered to someone else, if we modify it at this time, it is likely to affect other users who are already using the Function.

The adorner perfectly follows this open closure Principle.

four, The main function of the adorner and the fixed structure of the adorner

The main functions of the Adorner:

The function is added before and after the function without changing the method of function Invocation.

Fixed format for adorners:

def Timer (func):     def inner (*args,**kwargs):        ' ' '          before executing function ' = Func (*args,**Kwargs)         " " what to do after the function is executed ""        return re     return Inner
fixed format for adorners

five, with parameters of the adorner

Not to be continued

Preview Answer:

#to write an adorner, to add authentication functions to multiple functions (the User's account password originates from a file), requires a successful login,#subsequent functions do not need to enter the user name and password#tag = TrueTag =[True]defRZ (func):defInner ():#Global Tag        #while tag:         whiletag[0]: name= Input ("please Input your name:"). strip () passworld= Input ("please Input your passworld:"). strip () with open ("demo.py",'R', encoding='Utf-8') as Read_f:Print()                ifRead_f.readline () = = name+"\ n"  andRead_f.readline () = = passworld+"\ n" :                    #tag = Falsetag[0] =False func ()returnInner@rzdeffunc ():Print("Lln") @rzdeffunc1 ():Print("lln1") @rzdefFunc2 ():Print("LLN2") func () func1 () func2 ()
Preview the answer

Python function (3): 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.