Python full stack development-Day10 decorator (closed function application), python-day10

Source: Internet
Author: User
Tags ldap

Python full stack development-Day10 decorator (closed function application), python-day10
I. decorator

The decorator is an Application Scenario of closure functions.

What is a closure function? Let's recall:

Closure functions:

A function defined within a function. The function contains a reference to the external function scope (emphasizing that the reference to the global scope name is not a closure). This function is called a closure function.

When it comes to scope, let's recall:

 

Scope:
Global scope: built-in + global
Global validity and global survival
Local scope: Local
Local effect, local survival
The scope relationship is defined in the function definition stage and is irrelevant to the call location,
That is to say, no matter where the function is called, you must return to the location where the function was originally defined to find the scope.

 

I. Why do I need a decorator?

# Principle of open and closed: # once the software is launched, it should follow the principle of open and closed. It is closed for modifying the source code and open for Function Extension, that is, we must find a solution: # Add new functions to the function without modifying the source code and calling method of a function.

2. What is a decoration device?

# The decoration appliance of another user can be any callable object, and the decoration can also be any callable object. # Emphasize the decorator principle: #1. do not modify the source code of the decorated object #2. do not modify the call method of the decorated object # The decorator's goal: # Add new functions for the decorated object following the conditions of 1 and 2

Iii. Use of decorator

# Now we add the runtime Function import timedef index (): time. sleep (3) print ('Welcome to index page') # modify def index (): start_time = time. time () time. sleep (3) print ('Welcome to index page') stop_time = time. time () print ('run time is % s' % (stop_time-start_time) index () # function implementation # comments: directly change the source code, so it was opened...
# Use another boot to implement the function # modify import timedef index (): time. sleep (1) print ('Welcome to index page') start_time = time. time () index () stop_time = time. time () print ('run time is % s' % (stop_time-start_time) # comment: there are many functions to implement this function, write N times to change this code, # In the later stage, the maintenance service was forced or opened...
# Another child boots with repeated functions # use a powerful function # Revision 3: import timedef index (): time. sleep (3) print ('Welcome to index page') def wrapper (func): # func = index start_time = time. time () func () # index () stop_time = time. time () print ('run time is % s' % (stop_time-start_time) wrapper (index) # comment: modified the method of calling the original function, and is still enabled...
# Finally, I came to the calf's boot. The function value can be returned, and I will redefine the index # Revision 4: import timedef index (): time. sleep (3) print ('Welcome to index page') def outter (func): # func = original index def wrapper (): start_time = time. time () func () stop_time = time. time () print (stop_time-start_time) return wrapperindex = outter (index) # New index = wrapperindex () # basic implementation of the wrapper () function # comment: No returned value in the original value is OK, however, if a return value exists, the returned value is None.
# This time the calf boots passed by to see this situation, say so! # Revision 5 import timedef index (): time. sleep (1) print ('Welcome to index page ') return 123 # If 123 is returned here, the return value can be of any type #============= the decorator def timmer (func) is shown below ): # func = original index def wrapper (* args, ** kwargs): # variable length parameter start_time = time. time () res = func (* args, ** kwargs) # Call the original index stop_time = time. time () print (stop_time-start_time) return res # index () Run return value return wrapperindex = timmer (index) # New index = wrapperprint (index () # The function has been implemented, return Value 123 # comment: the decoration function has been implemented here, and the returned value is also obtained. The calf is not called by white.
# The sky is so colorful that the boots of Daniel appear! All of you are watching! Import timedef timmer (func): def wrapper (* args, ** kwargs): start_time = time. time () res = func (* args, ** kwargs) stop_time = time. time () print (stop_time-start_time) return res return wrapper @ timmer # index = standard format of timmer (index! Def index (): time. sleep (1) print ('Welcome to index page') return 123 @ timmer # home = timmer (home) def home (name): time. sleep (2) print ('Welcome % s to home page' % name) # index () # home ('egon') # comment: Daniel is Daniel! Daniel say: I want to teach you some technical skills. If you don't have any child boots, you can follow the template below: # No parameter modifier template def outer (func): # outer, inner name function random def inner (* args, ** kwargs): res = func (* args, ** kwargs) return res return inner @ outer # decorator must be at the top of the decoration function def duoduo (): pass

4. decorator syntax

# The top side of the decorated function, with a single line @ deco1 @ deco2 @ deco3def foo (): pass # foo = deco1 (deco2 (deo3 (foo ))) # The idea here is the top decorator. All the functions (deco2, deo3, foo) below the decoration # deco2 Decoration (deo3, foo ), finally, deo3 decorated foo # functions are different, so pay attention to the order of placement. Otherwise, the decoration effect may be incorrect!

5. Use of multiple decorators:

Import timecurrent_user = {'username': None, # 'login _ time': None} def auth (func): # func = index def wrapper (* args, ** kwargs ): if current_user ['username']: # It is authenticated. Next time you do not need to authenticate print ('already logged in ') res = func (* args, ** kwargs) return res uname = input ('user name >> :'). strip () pwd = input ('password >> :'). strip () if uname = 'egon' and pwd = '000000': print ('login successful ') current_user ['username'] = uname res = func (* args, ** kwargs) return res else: print ('username or password error') return wrapperdef timmer (func): def wrapper (* args, ** kwargs): start_time = time. time () res = func (* args, ** kwargs) stop_time = time. time () print (stop_time-start_time) return res return wrapper @ timmer # timmer calculates the execution time of auth + index @ auth # If we only decorate the index, we need to keep @ timmer behind indexdef index (): time. sleep (1) print ('Welcome to index page') return 123 @ auth @ timmer # Here, the count is the def home (name): time. sleep (2) print ('Welcome % s to home page' % name) # index () # home ("duoduo ")

6. Use of a parameter-based decorator:

Import timecurrent_user = {'username': None, # 'login _ time': None} def auth (engine): # The truth is that, enter an engine value # engine = 'file' # What does this value wear? def au22.: # func = index def wrapper (* args, ** kwargs): if engine = 'file': if current_user ['username']: print ('logged in already ') res = func (* args, ** kwargs) return res uname = input ('user name >> :'). strip () pwd = input ('password >> :'). strip () if uname = 'egon' and pwd = '000000': print ('login successful ') current_user ['username'] = uname res = func (* args, ** kwargs) return res else: print ('user name or password error') elif engine = 'mysql': # print ('myql-based Authentication ') elif engine = 'ldap ': print ('ldap-based Authentication') return wrapper return au22. # Here we also need to return au2's memory address @ auth ('ldap ') # @ au2# index = au22 (index) # index = wrapperdef index (): time. sleep (1) print ('Welcome to index page') return 123 index () # wrapper ()

 

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.