[2020Python practice 18] Introduction to Python syntax - function object + function nesting + closure function

Catalog

1. Function object

2. Function nesting

3. Closure function

3.1 what is closure function

3.2 how to define closure function

3.3 why there should be closure function -- application scenario of closure function

 

1. Function object

Function object: a function can be treated as data.

# func=Memory address

def func():
    print('from func')

func()

Output results: from func

 

It can be divided into four aspects:

(1) Functions can be referenced

# func=Memory address
def func():
    print('from func')

f=func  # take func Memory address to f

print(f,func)  #The output is f func Memory address of
f() #Calling function f


Output results:
<function func at 0x000001CF11CCA0D0> <function func at 0x000001CF11CCA0D0>
from func

 

(2) Function can be an element of container type

 

# func=Memory address
def func():
    print('from func')

l=[func,]
print(l)
l[0]()

dic={'k1':func}
print(dic)
dic['k1']()

//Output results:
[<function func at 0x000001B6BC12A0D0>]
from func
{'k1': <function func at 0x000001B6BC12A0D0>}
from func

 

(3) Function can be passed as an argument to another function

def func():
    print('from func')

def foo(x):      #  foo(func),  x = func Memory address of
    print(x)      #First output func Memory address of
    x()             # x=func Memory address of, x()Amount to func()

foo(func)        # foo(func Memory address of) #Call function foo


//Output results:
<function func at 0x000001C3AEF4A0D0>
from func

 

# func=Memory address
def func():
    print('from func')

def foo(x):     # x = func Memory address of
    # print(x)
    x()

foo(func)       #Namely  foo(func Memory address of)

//Output results:
from func

 

(4) The return value of a function can be a function

# func=Memory address
def func():
    print('from func')

def foo(x): # x=func Memory address of
    return x # return func Memory address of

res=foo(func) # foo(func Memory address of)
print(res) # res=func Memory address of

res()

//Output results:
<function func at 0x000001C3AEF4A0D0>
from func

 

2. Nesting of functions

(1) Nested definition of function: define other functions within the function

def f1():
    def f2():
        pass

 

(2) Nested call of function: call another function in the process of calling one function

def max2(x,y):
    if x > y:
        return x
    else:
        return y


def max4(a,b,c,d):
    # Step 1: compare a,b obtain res1
    res1=max2(a,b)
    # Step 2: comparison res1,c obtain res2
    res2=max2(res1,c)
    # Step 3: comparison res2,d obtain res3
    res3=max2(res2,d)
    return res3

res=max4(1,2,3,4)
print(res)

What a big chestnut

# circular
# Circumference of circle: 2*pi*radius
def circle(radius,action=0):
    from math import pi

    def perimiter(radius):
        return 2*pi*radius

  # To find the area of a circle: pi*(radius**2)
    def area(radius):
        return pi*(radius**2)

    if action == 0:
        return 2*pi*radius

    elif action == 1:
        return area(radius)

circle(33,action=0)

 

3. Closure function

[premise]

Based on the concept of function object, function can be returned to any place to call,

However, the scope relationship is determined when the function is defined, regardless of the call location of the function.

That is to say, when a function is treated as data processing, it always depends on its own scope.

 

Closure function = namespace and scope + function nesting + function object
Core point: the search relationship of names is based on the function definition stage

 

(1) what is a closure function

When a function is treated as data, its own scope always prevails. If an embedded function contains a reference to a variable in the scope of an external function (not the global scope), then the 'embedded function' is a closure function, or closures for short.

"Closed" function refers to the function is an embedded function

The package function refers to a function that contains a reference to the name of the scope of the outer layer function (not the global scope)

Therefore, no matter where the closure function is called, the variables wrapped in its outer layer are still used.

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

func=outer()
func() # The result is 2

You can view the external variables wrapped by the closure function through its closure property.

>>> func.__closure__
(<cell at 0x10212af78: int object at 0x10028cca0>,)
>>> func.__closure__[0].cell_contents
2

 

(2) How to define closure function

1) Closure function: application of namespace and scope + function nesting

def f1():
    x = 33333333333333333333
    def f2():
        print(x)
    f2()


x=11111
def bar():
    x=444444
    f1()

def foo():
    x=2222
    bar()

foo()


//Output results:
33333333333333333333

 

2) Closure functions: function objects

def f1():
    x = 33333333333333333333
    def f2():
        print('function f2: ',x)
    return f2

f=f1()
# print(f)

# x=4444
# f()
def foo():
    x=5555
    f()

foo()

//Output results:
//Function f2: 33333333333333333333

(3) Why there should be closure function -- the application of closure function

There are two methods of function body parameter transfer:

Mode 1: directly define the parameters required by the function body as forming parameters

def f2(x):
    print(x)

f2(1)
f2(2)
f2(3)

Mode 2: package values to functions

def f1(x): # x=3
    x=3
    def f2():
        print(x)
    return f2

x=f1(3)
print(x)

x()

And a big chestnut:

import requests # Function template needs to be downloaded in advance

//Scheme 1 of parameter transfer:
def get(url):
    response=requests.get(url)
    print(len(response.text))

get('https://www.baidu.com')
get('https://www.cnblogs.com/linhaifeng')
get('https://zhuanlan.zhihu.com/p/109056932')


//Scheme II of parameter transfer:
def outter(url):
    # url='https://www.baidu.com'
    def get():
        response=requests.get(url)
        print(len(response.text))
    return get

baidu=outter('https://www.baidu.com')
baidu()

cnblogs=outter('https://www.cnblogs.com/linhaifeng')
cnblogs()

zhihu=outter('https://zhuanlan.zhihu.com/p/109056932')
zhihu()


This property of closure function is sometimes called lazy computation. The way you package values to functions will also be useful in the decorator described in the next blog post.

Tags: Python

Posted on Fri, 20 Mar 2020 10:58:17 -0400 by ruach