Beginner python--Decorator

Source: Internet
Author: User
Tags home screen

first, what is an adorner

When we make a product, we need to maintain it continuously and add some functions to some functions. It would be very inappropriate to modify the source code at this time. (Reason: 1. A function that has been written in principle does not modify it as soon as possible, since the modification may result in unpredictable errors or reduced stability.) 2. Functions may be called many times, and if modifying a function may result in a change in the calling method, there will be a lot of modifications. So, the adorner appears. It is possible to add new functionality to a function without modifying the source code of the function itself.

second, the principle of the adorner

1. Cannot modify the source code of the modified function

2. Cannot modify the calling method of the modified function

third, realize the knowledge reserve of the decorator

1. A function is a "variable": Defines a function that is equivalent to assigning a function body to the variable of the function name.

2. Higher order function: a function that satisfies one of the following two conditions is a higher order function: ① pass the function name as an argument to another function ② the return value contains the function name

3. Nested functions: Functions can be nested

iv. use of adorners

Higher order function + nested function = Adorner

The essence of an adorner is a function that adds additional functionality to other functions

# There are now two functions, each with its own function, and the requirement is to calculate the time each function runs def Text1 ():    time.sleep (2)    print("This istext1" )def text2 (*args,**Kwargs):    time.sleep (2)    Print ("This istext2", Args[0],args[1])

Can write adorners:

def Timer (func):     def deco (*args,**Kwargs):        start_time=time.time ()        func (*args,**Kwargs)        end_time=time.time ()        print("Thefunction tun time is {0}  ". Format (end_time-start_time))    return deco

where the Func () function is the actual execution of the original function, and the other statements within the DECO function are the newly added functions of the statement

Decorator named timer

Would it be all right to write the decorator? No, one more step, add a statement above the original function, and combine it together:

defTimer (func):defDeco (*args,**Kwargs): Start_time=time.time () func (*args,**Kwargs) End_time=time.time ()Print("The function tun time is {0}". Format (end_time-start_time)) returnDeco@timer#The function of this action is to add the function of the adorner to the original function equivalent to Text1=timer (Text1)defText1 (): Time.sleep (2)    Print("This is Text1") @timer#without a @timer statement, the adorner function is not addeddefText2 (*args,**kwargs):#if the original function has parameters, you need to add parameters to Deco in the adorner.Time.sleep (2)    Print("This is text2", args[0],args[1]) Text1 ()#does not change the invocation mode and adds new functionalityText2 (29000,"Hello")

Adorner parsing: The Deco function is used to implement new functionality, and the timer function and the @timer statement are used to make the calling method unchanged

Execution Result:

five, with parameters of the adorner

This is not about the original function with parameters, but the adorner function itself with parameters

Now there is a need to use the decorator to implement the landing process, and there are two different ways of landing: using local data to log in and use the cloud data landing

#now there are three pages, which log in home with local data, when landing BBS with cloud datadefindex ():Print("Welcome to Index page")defHome ():Print("Welcome to Home Page")    return "Form Home"defBBS ():Print("Welcome to BBS page")

Decorator Required:

Name="Alex"Word="123"defAuth (auth_type):defAuth_out (func):defDeco (*args,**Kwargs):ifauth_type=="Local":#If you use local dataUesrname=input ("Please enter user name:"). Strip () password=input ("Please enter your password:"). Strip ()ifUesrname==name:#If the user exists                    ifPassword==word:#If the password is correct                        Print("using local Data")                        Print("Welcome to the entrance! ")                        returnFunc (*args,**kwargs)#go to the home screen                    Else:                        Print("Password Error")                Else:                    Print("user does not exist")            elifauth_type=="Cloude":#If you use cloud data                Print("Use cloud Data")                Print("Welcome") func ()#Enter BBS interface        returndecoreturnAuth_outdefindex ():Print("Welcome to Index page") @auth (Auth_type="Local")#log in to the home interface using local user data, in the AUTH () incoming parameterdefHome ():Print("Welcome to Home Page")    return "Form Home"@auth (Auth_type="Cloude")#Login BBS interface to use cloud user datadefBBS ():Print("Welcome to BBS page") index ()Print(Home ()) BBS ()

In fact, the original adorner is nested inside the outer layer of a function, used to pass parameters. The @ statement also becomes @auth (auth_type= "")

Operation Result:

Beginner python--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.