Closure function, decorator

Keywords: PHP Python

I. supplementary knowledge points

1. callable (can be parenthesized to perform a specific function): function name, class name

2. import this: View Python Zen

Closure function

1, definition

Closed: a function defined within a function

Package: the inner function references the name of the outer function scope

2, form

def outter(x,y):
    def inner():
        //Code 1
        //Code 2
        return inner

res = outter(1, 2)
res()

3, role

There are two ways to pass parameters to function bodies. The first way is to pass parameters directly to function bodies. The second way is to use closure functions. It uses external functions to pass parameters to internal functions. In this way, when calling internal functions, parameters are not written.

4. Examples

import requests  # requests is an easy-to-use HTTP library implemented by python
def outter(url):
    def my_get():
        response = requests.get(url)
        if response.status.code == 200:
            print(len(response.text))
        return my_get
my_jd = outter("https://www.jd.com")
my_jd()

III. decorator

1, definition

Tool: it's a tool

Decoration: add new functions to the decorated objects

2. Open and closed principle

Open: open to expansion

Closing: closing for changes

3. Two principles to be followed for decorators

①. Do not change the source code of the decorated object

②. Do not change the call mode of the decorated object (callable object)

4. Simple version of decorator

"""
//Count the execution time of index function
"""
import time  # Import time module
def index():
    time.sleep(1)
#Let the program pause for 1 second. When measuring the running time of the program, if the time is too short, the measuring time will be 0, plus the delay, it can be measured.
    print('Macau's largest online casino opened sexy tank Online licensing!')

def outter(func):  # func = memory address of the original index function
    def get_time():
        start = time.time()
        func()  # Func = memory address () of index function called directly
        end = time.time()
        print('index run time:%s'%(end-start))
    return get_time
index = outter(index)  # Outer (original index function memory address)
# index refers to the memory address of get time function
index()

5. Decorator upgrade

It solves the problem of function parameters. Both nonparametric and parametric functions can be called directly and can receive any number of parameters.

 

import time
def index():
    time.sleep(1)
    print('from index')
    return index
res = index()  # from index

def login(name):
    time.sleep(1)
    print(name)
    return login
res1 = login('egon')  # egon

def outter(func):
    def get_time(*args, **kwargs):
# Any parameter can be passed in and put into tuples and dictionaries
        start = time.time()
        res = func(*args, **kwargs)
# Break tuples and dictionaries and pass parameters to func function intact
        end = time.time()
        print(end-start)
        return res
    return get_time

index = outter(index)  
login = outter(login)
index()
# from index
# 1.0002615451812744
# At this time, index() has more timing functions.
login('egon')
# egon
# 1.0002918243408203
# At this time, login() has more timing functions.
print(res)
# <function index at 0x00DFA660>
print(res1)
# <function login at 0x028435D0>
print(index)
# <function outter.<locals>.get_time at 0x028436F0>
print(login)
# <function outter.<locals>.get_time at 0x02843660>

6. Decorator grammar sugar

Posted by pgosse on Wed, 30 Oct 2019 08:38:01 -0700