"Python"--adorners, iterators, generators

Source: Internet
Author: User

Decorative Device

An adorner is essentially a function that is used to decorate other functions, as the name implies, to add attachments to other functions.

First, the adorner principle:
    1. Cannot modify the source code of the decorated function

    2. Cannot modify the calling method of the decorated function

def logging ():     Print ("logging ... "  # correct wording, no modification source def  test1 ():    pass#  Wrong wording, cannot modify source def  test1 ():    pass    #  Call Way, Can not be modified test1 ()
View Code

Second, the adorner knowledge:
    1. function is "variable"
    2. Higher order function + nested function = "Adorner"
1, function is "variable"

Python's memory mechanism, see the following code:

# variable x = 1# function def  Test ():    Pass

This is represented in the memory diagram:

X, test is the variable name, stored in the stack memory, 1, the function body is stored in the heap memory

2. Higher order function + nested function = "Adorner"

Decorator implementation process:

First step: Original code

def Home ():     Print ("---home----"def  TV ():    print(" ----TV---- " )def  Music ()    print("---music-----" )
View Code

Second step: Want to add a login authentication to some modules

User_status = False#when the user logs in, change this to true. deflogin (): _username="ABC" #Pretend this is the user information stored in the DB ._password ="12345" #Pretend this is the user information stored in the DB .    GlobalUser_statusifUser_status = =False:username= Input ("User:") Password= Input ("Pasword:")         ifUsername = = _username andPassword = =_password:Print("Welcome login ....") User_status=TrueElse:            Print("wrong username or password!")    Else:        Print("user is logged in, verified by ...") defHome ():Print("---home----") defTV (): Login ()#pre-execution plus validation    Print("----TV----") defmusic ():Print("----Music----")
View Code

Although this realizes the authentication function, but modifies the adornment function the source code, violates the adorner principle "cannot modify the source of the adornment function"

The third step: Code improvement, using the high-order function concept, the function name when the parameters passed to the authentication function login, so that can not modify the source code of the decorated function to complete the login authentication

User_status = False#when the user logs in, change this to true. defLogin (func): _username="ABC" #Pretend this is the user information stored in the DB ._password ="12345" #Pretend this is the user information stored in the DB .    GlobalUser_statusifUser_status = =False:username= Input ("User:") Password= Input ("Pasword:")         ifUsername = = _username andPassword = =_password:Print("Welcome login ....") User_status=TrueElse:            Print("wrong username or password!")    ifUser_status = =True:Print("user is logged in, verified by ...") func ()#as long as the validation passes, the function is called defHome ():Print("---home----") defTV ():Print("----TV----") defmusic ():Print("----Music----") Login (TV)#Call Login to validate, and pass the function that needs to be validated as a parameter to login
View Code

Although this can be done without modifying the source code of the decorated function to complete the login authentication, but contrary to the adorner principle "modified the call method of the decorated function", originally decorated function only need TV () can be called, now become login (TV)

Fourth Step: Code improvements, using the anonymous function concept, the login (TV) into TV = login (TV), the function as a value, assigned to the variable name TV, with the keyword def redefined the TV is the same effect, but there is a problem, TV = login (TV) This assignment process , you put

function TV to call, the user has not been called, the automatic call itself is not correct, this time need to use the concept of nested functions, in the authentication function login inside the definition of a new function Login_inner, the login function return (return) Login_ The inner function name (for return Login_inner, not return Login_inner (), because the return function name returns the memory address of the function on the stack contents, return function name + () returns the execution result of the function) so that the TV = L When Ogin (TV) is assigned, the TV assignment is not the result of login (TV), the value of the assignment is Login_inner memory address, and so on when the user calls the TV (), so there is no change in the method of the call of the decorated function.

Adorner decoration no parametric function:
Import Time#Defining Adorner functionsdefTimmer (func):#Pass the Test1 function name as a parameter in the Func=test1    #defining built-in functions in adorners    defdeco (): Start_time=time.time () func ()#equivalent to Running Test1 ()Stop_time =time.time ()Print("The func run time is%s"% (stop_time-start_time)) returndeco#Decorative test1 function@timmer#equivalent to test1 = Timmer (test1)deftest1 (): Time.sleep (3)    Print("In the test1") #Execute the test1 function directlytest1 ()#OutputinchThe test1the func run time is3.0002999305725098

"Python"--adorners, iterators, generators

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.