Function objects closure Python-

A function object

Refers to the function object can be treated as a function of the "data" to process, particularly use can be divided into four areas.

1.1 function can be referenced

def index():
    print('from index')
a = index
a()

1.2 can be used as parameter transfer function

def foo(x,y,func):
    print(x,y)
    func()
    
def bar():
    print('from bar')

foo(1,2,bar)
#>>> 1 2
#>>> from bar

1.3 function name can be used as the return value

def index():
    print('from index')
    
def func(a):
    return a
    
a = func(index)
a()
#>>> from index

1.4

Function name can be used as an element of a container type

def func():
    print('from func')
    
l1 = [1,'2',func,func()]

f = l1[2]

#>>> from func

Two closure function

2.1 and closure package

Based on the concept of the object function, the function can be returned to any location to call, but the relationship is in the scope of the definition of complete function has been determined, regardless of the location of the function call.

x = 1

def f1():
    def f2():
        print(x)
    return f2
    
def f3():
    x = 3
    f2 = f1() # 调用f1()返回函数f2
    f2() # 需要按照函数定义时的作用关系去执行,与调用位置无关
f3() # 结果为1

That is the function are treated as data processing, always comes with the scope prevail. If the function contains embedded reference to the external scope (not global scope) variables, then the 'nested function' is a function closure referred closure (closeures)

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

func = outer()
func() # 结果为2

2.2 The use of closures

So far, we have two kinds of traditional values ​​as a function of the way, a direct pass values ​​as parameters, another is a function of the value of contracted out

# 直接传参
def func(x):
    print(x)
    
    
func(1000)


# 通过闭包函数传参
def outer(number):
    # number = 1000
    # inner就是闭包函数
    def inner()
        print(number)
    return inner
    
func = outer(1000) # ---》 inner地址 ---》 func变量名
func() # func ---> inner地址()

This characteristic closure function sometimes referred to as lazy evaluation. The value passed to the function using the embodiment, will be of great use in the decorator!

Guess you like

Origin www.cnblogs.com/snailhuang/p/11892636.html