Python 3 Learning Note (vi)----decorator

Source: Internet
Author: User
Tags ldap

First, the definition

An adorner is essentially a function that decorates other functions and adds additional functionality to other functions.

Second, the adorner principle

1. Cannot modify the source code of the decorated function

2. Cannot modify the calling mode of the decorated function

Third, the realization of the necessary knowledge of adorners

1. A function is a variable

1 #def foo ():2 #print ("in the Foo")3 #Bar () #bar未定义4 #foo ()5 6 7 #def Bar ():8 #print ("int the bar")9 #def foo ():Ten #print ("in the Foo") One #Bar () A #foo () -  -  the #def foo (): - #print ("in the Foo") - #Bar () - #def Bar (): + #print ("int the bar") - #foo ()
1 def foo (): 2     Print ("in thefoo") 3     Bar ()4foo ()5def Bar ():  # after a call, the definition does not execute 6     Print ("int the bar")

2. Higher-order functions (two representations of higher-order functions)

2.1 Pass a function name as an argument to another function (add a function to it without modifying the source code of the decorated function)

1 Import Time2 3  defBar ():4Time.sleep (3)5      Print("In the bar")6 7  defTest1 (func):8Start_time =time.time ()9 func ()TenStop_time =time.time () One      Print("The func run time is%s"% (stop_time-start_time)) ATest1 (BAR)

2.2 The return value contains the function name

1 Import Time2 defBar ():3Time.sleep (3)4     Print("In the bar")5 defTest2 (func):6     Print(func)7     returnFunc#return to memory address8 9 #Print (Test2 (bar))Ten #T=test2 (BAR) One #t () #run bar ABar=test2 (BAR) -Bar ()#the returned memory address plus () can be executed

3. Nesting functions

1x=02 defA ():3X=14     defb ():5x=26         defC ():7X=38             Print(x)9 C ()TenB ()#if B () is not executed here, then the function is equal to nothing, because there is no print OneA ()

Decorator = higher order function + nested function

1 Import Time2 3 defTimer (func):#timer (test) Func=test4     defdeco ():5Start_time =time.time ()6Func ()#The decorated function test is run here7Stop_time =time.time ()8         Print("Func Run time is%s"% (stop_time-start_time))9     returnDeco#returns the memory address of DecoTen  One  A@timer#equivalent to Timer=timer (test), the adorner is always placed before the decorated function - defTest (): -Time.sleep (3) the     Print("This is test") -  -Test ()

V. If the function of the adorner contains parameters

1 Import Time2 3 defTimer (func):4     defDeco (*args,**kwargs):#*args,**kwargs means that the parameter is indeterminate5Start_time=time.time ()6Func (*args,**Kwargs)7Stop_time=time.time ()8         Print("In the run time is %s"% (stop_time-start_time))9     returndecoTen  One@timer#test2 = Timer (test2) = Deco test2 (name) = Deco (name) A deftest2 (age,name,job): -Time.sleep (1) -     Print("test2:", Age,name,job) the  -Test2 (23,"Irlo","Seller")

Vi. examples of use of adorners

Suppose you add a login verification for a Web page

1USER,PASD ="Irlo","12345"2 defAuth (auth_type):3     Print("auth func is", Auth_type)4     defType (func):5         defwrapper ():6             ifAuth_type = ="Local":7Username = input ("Username:"). Strip ()#strip remove characters from the end of a string (the default is a space)8Password = input ("Password:"). Strip ()9                 ifUser==username andpasd==Password:Ten                     Print("\033[1;32;1mauthority of account\033[0m")#highlighted format (\033[display; foreground color; background colour m) OneRes=func ()#Assign the result to a variable before calling home with results A                     Print("After authentication") -                     returnRes#If you do not return, the equivalent of execution is finished, no return value is a null value -                 Else: the                     Print("Invalid username or password") -             elifAuth_type = ="LDAP": -                 Print("I just know local,fuck off") -         returnwrapper +     returntype -  + defindex (): A     Print("Welcome to Index page") at  -@auth (Auth_type ="Local") - defHome (): -     Print("Welcome to Home Page") -     return "From home" -  in@auth (Auth_type ="LDAP") - defBBS (): to     Print("Welcome to BBS page") +  - index () the Print(Home ())#calling home is the equivalent of calling wrapper * Home () $BBS ()

Python 3 Learning Note (vi)----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.