Categories
Uncategorized

8. Function – closure

First, the function name

⼀ function name is variable, but it is ⼀ a special variable, and can be performed with parentheses variable ⾏ function.

1. The memory address of the function name

def func():
    print("呵呵")
    print(func)
结果:

2. The function name can be assigned to other variables

def func():
    print("呵呵")
    print(func)
# 把函数当成⼀个变量赋值给另⼀个变量
a = func
# 函数调⽤ func()
a() 

3. The function name can be used as function parameters

def func():
    print("吃了么")
def func2(fn):
    print("我是func2")
    fn() 
    print("我是func2")
# 把函数func当成参数传递给func2的参数fn.
func2(func) 

4. The name can be used as the return value of the function

def func_1():
    print("这⾥是函数1")
def func_2():
    print("这⾥是函数2")
    print("这⾥是函数1")
    return func_2
# 执⾏函数1. 函数1返回的是函数2, 这时fn指向的就是上⾯函数2
fn = func_1()
# 执⾏上⾯返回的函数
fn()    

Second, closure

1. Definitions

If an internal function, the variable to be applied externally to (but not in the global scope) references, then the internal function is considered to be closure.

Closure (the Closure) lexical closures (Lexical Closure) for short, is a function of the free variables cited. This free variables referenced and this function will exist together, even if it has left the creation of an environment is no exception. Therefore, the closure is a combination of entities associated with a function and a reference environment formed.

Popular talk is: If an internal function, the pair (but not in the global scope) were variable reference outside the scope, then the internal function is considered to be closure (closure). It is just a “inner” function by a name (variable) to refer to, and the name (variable) for “outer layer” contains in terms of its function, it is a local variable.

The main purpose of closure: realized decorator

2. Closure use

    Closure function must have built-in functions

    Namespace references an inline function requires the nested function variables

    Closures function must return the built-in functions

(1) Normal closure

def func(a, b):
    def line(x):
        return a * x - b
    return line

line = func(2, 3)
print(line(5))

(2) modification value closure

def func(a, b):
    def line(x):
        nonlocal a
        a = 3
        return a * x - b
    return line

line = func(2, 3)
print(line(5))

Leave a Reply