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

Time:2020-12-2

 

catalog

1. Function object

2. Function nesting

3. Closure function

3.1 what is a closure function

3.2 how to define closure function

3.3 why there is a closure function — application scenarios of closure functions

 

1. Function object

Function object: function can be treated as data.

#Func = memory address

def func():
    Print ('from func ') func() output result: from func

 

It can be divided into four aspects

(1) Function can be referenced — F = func

 

#Func = memory address
def func():
    print('from func')

F = func ා pass the memory address of func to F

Print (F, func) ා outputs the memory address of F func
F() ා call function f output result: from func

 

(2) Function can be an element of container type — L = [func,]

 

 

#Func = memory address
def func():
    print('from func')

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

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

Output results:
[]
from func
{'k1': }
from func

 

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

 

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

Def foo (x): # foo (func), x = memory address of func
    Print (x) ා output the memory address of func first
    X () ා x = memory address of func, X () is equivalent to func ()

Foo (func) # foo (memory address of func) # call function foo


Output results:

from func

 

#Func = memory address
def func():
    print('from func')

Def foo (x): # x = memory address of func
    # print(x)
    x()

Foo (func) ා i.e. foo (memory address of func)

Output results:
from func

 

(4) The return value of a function can be a function – return function name – note: there is no extension

#Func = memory address
def func():
    print('from func')

Def foo (x): # x = memory address of func
    Return x ා the memory address of return func

Res = foo (func) # foo (memory address of func)
Print (RES) # res = memory address of func

res()

Output results:

from func

 

2. Nesting of functions

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

def f1():
    def f2():
        pass

 

(2) Nested calls of functions: in the process of calling a function, other functions are called

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


def max4(a,b,c,d):
    #Step 1: compare a and B to get res1
    res1=max2(a,b)
    #Step 2: compare res1 and C to get res2
    res2=max2(res1,c)
    #Step 3: compare res2, D to get res3
    res3=max2(res2,d)
    return res3

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

What a big chestnut

#Round
#Find the circumference of a circle: 2 * pi * radius
def circle(radius,action=0):
    from math import pi

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

  #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, the function can be returned to any place to call,

However, the relationship between scopes is determined when the function is defined, regardless of the calling position of the function.

That is to say, when a function is treated as data, its own scope will always prevail.

 

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 closure function

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

A “closed” function means that the function is an embedded function

A “package” function means that the function contains a reference to the scope name of the outer function (not to the global scope)

Therefore, wherever a closure function is called, the variables wrapped around it 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 the function’s closure property.

>>> func.__closure__
(,)
>>> 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 is a closure function — the application of closure function

There are two ways to transfer parameters to function body

Method 1: define the forming parameters directly according to the parameters required by the function body

def f2(x):
    print(x)

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

Method 2: package the value to the function

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

x=f1(3)
print(x)

x()

Another big chestnut:

Import requests ා you need to download the function template in advance

The first scheme is to transmit the reference
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')


The second scheme is to transmit the reference
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. Wrapping values into functions will also be useful in the decorators that will be covered in the next blog post.

 

Recommended Today

#Zhang Xiaolong wants to like it: log in to Alibaba cloud with enterprise wechat?

Many enterprises are using enterprise wechat for organization management, and at the same time, they use Alibaba cloud services. We don’t want to create an alicloud sub account for each employee. If only we could log in directly using enterprise wechat. At this time, how to unify the user directory and achieve single sign on […]