Closure function and decorator of python syntax

Keywords: Python

I. closure function

1. What is a closure function

Closed: closed

Package: package

##1. The closure function must be defined inside the function

##2. Closure function can refer to the name of outer function

2. Closure function structure

def outer(x):
    def inner():
        print(x)
    return inner
inner = outer(2)
inner()

3. Parameter transfer method

3.1 direct reference

3.2 closure reference

4. Application of closure function

#Requirement: crawl a website and print the length of data

#Method 1: direct reference
import requests
def spider_func(url):
    response = requests.get(url)    #Send address request instruction to get response data
    if response.status_code == 200:  # Judge the status code, 200 indicates the access status is successful
        # print(response.text)      #Get data text
        print(len(response.text))   #Statistics length


url = 'https://www.baidu.com/'
spider_func(url)

#Method 2: receive url address through closure function and perform crawling data
import requests

def spider_func(url):
    def inner():
        response = requests.get(url)
        if response.status_code == 200:
            print(len(response.text))
    return inner
baidu = spider_func('https://www.baidu.com/')
baidu()

 

II. Decorator

1.1 what is a decorator

Decoration: decoration, decoration

Tool: tool

A decorative tool.

*****Open: the addition of function functions is open.

Closed: changes to function functions are closed.

1.2, role

Add new functions without modifying the source code and calling method of the decorated object.

1.3 definitions must be followed

The source code of the decorated object is not modified.

Does not change the way the decorated object is called.

1.4 why use closure function

It can solve the code redundancy and improve the code scalability.

1.5, use

Application: Statistics time, login authentication, log insertion, performance test, transaction processing, cache, permission verification, etc.

Example: demand:

Time to download movies

import time

def download_movie(*args,**kwargs):
    print('Start downloading movies...')
    time.sleep(3)
    print('Movie downloaded successfully')
    return 123

def outer(f):  #f = download_movie
    def inner(*args,**kwargs):
        star_time = time.time()
        res = f(*args,**kwargs)   #f(*args,**kwargs)----> download_movie(*args,**kwargs)
        end_time = time.time()
        print(f'The consumption time is:{end_time - star_time}')
        return res
    return inner
download_movie = outer(download_movie)
download_movie() 

 

2. Decorator grammar sugar

@: decorator's grammar sugar

Note: when using decorator syntax sugar, the decorator must be defined on the decorated object.

Example:

import time

def outer(func):     #Decorated object
    def inner(*args,**kwargs):  #Functions of decorated objects
        start_time = time.time()
        res = func(*args, **kwargs)
        end_time = time.time()
        print(f'Elapsed time:{end_time - start_time}')
        return res
    return inner
# download_movie = outer(download_movie)
# download_movie()
@outer
def download_movie():
    print('Start downloading movies...')
    time.sleep(3)
    print('Movie downloaded successfully')
    return 123
download_movie()

 



Posted by misterfine on Tue, 12 Nov 2019 11:03:56 -0800