闭包 closure

需要注意的是,
计算机可以看作是pure math的子集,这里只能提到一点皮毛,遇到了先行记录,等以后深入的时候再补充

先分析一下闭包是什么,然后通过看python,和js源码中的实现方式,来提升理解。
a function which closes over the environment(scope) in which it was defined

在函数中再嵌套一个函数,并且引用外部函数的变量

def outer(x):
    def inner(y):
        return x + y
    return inner

print(outer(6)(5))
-----------------------------
>>>11

python 装饰器(decorator)

def debug(func):
    def wrapper():
        print("[DEBUG]: enter {}()".format(func.__name__))
        return func()
    return wrapper

@debug
def hello():
    print("hello")

hello()
-----------------------------
>>>[DEBUG]: enter hello()
>>>hello

闭包的作用可以从他的概念上看出来,一个复杂函数内部的大量逻辑中,可能也有很多重复的处理逻辑部分,把这部门内容封装成复杂函数内部的函数,仅供复杂函数内部处理重复的逻辑,其实这就是闭包的作用吧,至于装饰器我感觉是正好闭包的实现结构符合了装饰器的结构,所以就用闭包来实现装饰器了

reference

python 装饰器详解

posted @ 2022-05-19 17:50  deadright  阅读(25)  评论(0)    收藏  举报