闭包结构的本质

闭包定义:
如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包;
闭包的概念:闭包(Closure)是词法闭包(Lexical Closure)的简称,是引用了自由变量的函数。这个被引用的自由变量将和这个函数一同存在,即使已经离开了创造它的环境也不例外。所以,闭包是由函数和与其相关的引用环境组合而成的实体。

采用比较说法就是,通常一个函数运行结束之后,内部变量就会被销毁释放,C就是这样;然而在闭包这种结构中,外部函数的局部变量在该函数运行之后,其内部变量值在竟然在其返回的内部函数中得到了保持,这是比较本质的内容!!

函数可以嵌套定义,即在一个函数内部可以定义另一个函数,有了嵌套函数这种结构,便会产生闭包问题。
这会产生一些好的操作!

偏函数,装饰器 是否采用了闭包机制 延迟了一个函数部分执行?
常用高阶函数接收函数作为参数,很有可能返回一个闭包。

理解装饰器的前提:1.所有东西都是对象(函数可以当做对象传递) 2.闭包

闭包的概念:
1)函数嵌套
2)内部函数使用外部函数的变量
3)外部函数的返回值为内部函数

闭包典型应用,装饰器->传入的参数都因此结构滞留在返回的函数中!滞留了传入的函数就变成该函数的装饰器。

Short answer: closure is the mechanism, while functools.partial and decorators are typical uses of that mechanism.

The key difference between a closure and more typical namespaces is that the names and values in the "closed-over" namespace don't vanish when control flow leaves the top-level function. They're preserved in a mini-namespace associated with one instance of the inner function, and which survives as long as that instance does.

functools.partial uses that ability to "remember" some arguments to a pre-existing function. Decorators also typically use that ability for the same reasons.

Note that a decorator is more flexible than that. Any callable that takes one parameter and returns something can serve as a decorator. It doesn't have to make use of Python closures, or even return a function. Many decorators return a callable object instead. (As an aside, a closure and inner function can be simulated using an object for the namespace and a method for the inner function.)

Whatever the decorator returns is assigned to the name the decorated function would have had. (Decorators with parentheses after them, like @decorator('args') ... are slightly more complicated.) The typical decorator syntax:

@decorator
def function():
pass
...is just a shorthand for "define, then decorate and reassign":

def function():
pass
function = decorator(function)
For an extreme (and mostly useless) example:

def decorator5(__):
return 5

@decorator5
def square(x):
return x * x

print(square) # Prints 5 --- the function is gone.
square(10) # TypeError: 'int' object is not callable

原文地址:https://www.cnblogs.com/wdmx/p/9955700.html