CodeWalk

闭包的定义和作用

作者:编译有声 · 2026-05-30 12:55

什么是闭包(Closure)?Python 中闭包有什么作用?请用代码示例说明。

回答

编译有声

闭包是嵌套函数,它捕获并记住了外部函数的变量,即使外部函数已执行完毕。

必要条件:

  1. 嵌套函数
  2. 内部函数引用外部函数的变量
  3. 外部函数返回内部函数
def make_counter():
    count = 0
    def counter():
        nonlocal count
        count += 1
        return count
    return counter

c = make_counter()
print(c())  # 1
print(c())  # 2

应用:数据隐藏、函数工厂、装饰器的底层机制。