闭包之作用

发布时间 2023-08-26 17:18:44作者: Allen_Hao

主要的作用和用途:

  1. 保存状态:闭包可以用于保存函数的局部变量状态,这样在每次调用函数时,闭包内的变量都会被保留下来。这使得闭包非常适合用于实现计数器、缓存等功能。

  2. 延迟执行:通过使用闭包,我们可以将某个操作延迟到稍后执行。例如,可以创建一个延迟调用的函数,该函数接受一些参数,并在稍后的时间执行特定的操作。

  3. 高阶函数的参数和返回值:由于闭包是函数对象,所以它可以作为高阶函数的参数或返回值。这使得我们可以在函数之间传递闭包,从而实现更复杂的功能。

  4. 封装:闭包可以将一组相关的数据和函数封装在一起,形成一个独立的实体。这样可以提高代码的可读性,并且避免全局变量的污染。

保存状态

 1 '''
 2 保存状态:通过闭包可以实现状态的保存。
 3 例如,下面的示例中,我们创建了一个计数器函数,每次调用返回增加1的值。
 4 '''
 5 def counter():
 6     count = 0
 7 
 8     def increment():
 9         nonlocal count
10         count += 1
11         return count
12 
13     return increment
14 
15 
16 c = counter()
17 print(c())  # 输出1  保存了外部函数变量count没有被回收
18 print(c())  # 输出2
19 print(c())  # 输出3

延迟执行

 1 '''
 2 延迟执行:闭包可以用于延迟执行某些操作。例如,下面的示例中,我们创建了一个延迟调用函数,它接受一些参数,并在稍后的时间执行特定的操作。
 3 '''
 4 
 5 
 6 def delayed_call(func, *args):
 7     def wrapper():
 8         return func(*args)
 9 
10     return wrapper
11 
12 
13 def say_hello(name):
14     print(f"Hello, {name}!")
15 
16 
17 # 虽然调用了外部函数,但实际上,业务没有执行,只是返回了引用,便于后面在适合的时间执行
18 delayed_say_hello = delayed_call(say_hello, "Allen")
19 # 在适合的时间执行特定的操作
20 delayed_say_hello()  # 输出 "Hello, Allen!"

闭包&高阶函数的应用

其实把闭包的外部函数的形参变成一个函数,外部函数就变成了高阶函数。

 1 # 1. 定义一个高阶函数(也是闭包的外部函数),有一个参数func(func就是函数引用)
 2 def my_higher_order_function(func):
 3     def wrapper():
 4         print("Before calling the closure function")
 5         func()
 6         print("After calling the closure function")
 7 
 8     return wrapper
 9 
10 
11 # 2. 定义一个函数
12 def my_closure_function():
13     print("Inside the closure function")
14 
15 
16 # 3. 将函数my_closure_function作为参数传递给高阶函数,获得闭包函数wrapper的引用
17 wrapped_function = my_higher_order_function(my_closure_function)
18 
19 # 4. 调用闭包函数,实际上会在my_closure_function函数前后分别打印信息
20 wrapped_function()

封装

 1 '''
 2 封装:闭包可以将一组相关的数据和函数封装在一起,形成一个独立的实体。这样可以提高代码的可读性,并且避免全局变量的污染。
 3 '''
 4 
 5 
 6 def create_student(name, age):
 7     def get_name():
 8         return name
 9 
10     def get_age():
11         return age
12 
13     def set_name(new_name):
14         nonlocal name
15         name = new_name
16 
17     def set_age(new_age):
18         nonlocal age
19         age = new_age
20 
21     return {
22         'get_name': get_name,
23         'get_age': get_age,
24         'set_name': set_name,
25         'set_age': set_age
26     }
27 
28 
29 student = create_student("Allen", 20)
30 print(student['get_name']())  # 输出 "Allen"
31 print(student['get_age']())  # 输出 20
32 student['set_name']("Bob")
33 print(student['get_name']())  # 输出 "Bob"