4.闭包函数

  • 把函数作为一个形参传递,叫做回调函数

  • 那么如果一个函数,返回了一个函数就叫闭包函数

  • 返回的内函数叫闭包函数,整个函数叫称为闭包

  • 要满足2个条件:

  1. 在外函数,return一个内函数
  2. 内函数还使用了外函数中的局部变量

"""
work是工作,调用1次外面的money变量就增加100,overtime函数,运行一次加200,如果再次给money变量赋值,那么会改变money全局变量.是有问题的
"""

money = 0
def work():
    global money
    money += 100


def overtime():
    global money
    money += 200

def buy():
    global money
    money -= 40

#调用3次,money变成了300
work()
work()
work()
overtime()
buy()
money = 0
print(money)

1.闭包函数示例:用闭包函数,改造上面的代码,就会不会修改全局变量

#定义1个函数
def person():
    money = 0  #在函数中定义了一个局部变量

    # 工作     在外函数中定义了内函数
    def work():
        nonlocal money  # 在内函数中使用了,外函数的临时变量
        money += 100
        print(money)

    # 在外函数中返回了内函数,这个内函数就是闭包函数
    return work


res = person()
res()
res()
res()
  1. 画图理解

结论

  • 此时,就不能够在全局中对money局部变量做任何操作
  • 闭包的作用:保护了函数中的变量,不受外部的应影响,该函数既能够修改,又能够使用

3.监测函数是不是闭包函数,如果是闭包函数,返回 cell ,不是闭包函数返回None

print(res.__closure__)
(<cell at 0x000002BDA7166640: int object at 0x000002BDA7176C70>,)
posted @ 2021-11-25 22:31  john5的博客  阅读(11)  评论(0编辑  收藏  举报
// 侧边栏目录 // https://blog-static.cnblogs.com/files/douzujun/marvin.nav.my1502.css