欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

[黑马程序员] Python 高级 - 关闭

最编程 2024-03-22 20:55:13
...

定义

  • 定义双层嵌套函数,内层函数可以访问外层函数的变量
  • 将内层函数作为外层函数的返回,此内层函数就是闭包函数
  • 代码示例
def out_func1(label):
    def in_func1(msg):
        print(f'{label}{msg}{label}')

    return in_func1


out = out_func1("边框")
out("hello")

nonlocal关键字作用

  • 在闭包函数修改外层函数的变量值
  • 代码示例
def outer_func(out_num):
    def in_func(in_num):
        # 修改外层变量
        nonlocal out_num
        out_num += in_num
        print(out_num)

    return in_func

优缺点

优点

  • 无需定义全局变量即可实现通过此函数,持续的访问、修改某个值
  • 闭包使用的变量的作用域在函数内部,难以被错误的调用修改

缺点

  • 由于内部函数持续引用外部函数的值,所以会导致这一部分内存空间不被释放

装饰器

  • 装饰器也是一种闭包
  • 功能:在不破坏目标函数原有代码和功能的前提下,为目标函数增加新功能

装饰器闭包写法

  • 定义一个闭包函数,在闭包函数内部
    • 执行目标函数
    • 完成功能的添加
  • 代码示例
# 装饰器语法糖写法
def outer1(func):
    def inner():
        print("start")
        func()
        print("end")

    return inner


@outer1
def sleep1():
    import random
    import time
    print("sleep...")
    time.sleep(random.randint(1, 5))


sleep1()

推荐阅读