码迷,mamicode.com
首页 > 其他好文 > 详细

闭包结构的本质

时间:2018-11-14 01:12:58      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:sid   square   ram   some   ted   something   rem   mini   name   

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

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

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

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

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

闭包结构的本质

标签:sid   square   ram   some   ted   something   rem   mini   name   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!