Rinne's Blog

Back

闭包的概念#

对于这样一个示例:

def outer_function(x):
    def inner_function(y):
        return x + y  # inner_function记住了outer_function的参数x
    return inner_function
python

函数 outer_function 在函数 inner_function 中,外部函数 outer_function 的所有变量对于内部函数 inner_function 都是可见的,反之不成立。

对于这样一个内部函数inner_function(对外部作用域的变量进行引用),被认为是闭包。 而且通常外部函数的返回值为内部函数。

闭包的用途#

对于上面的例子,我们可以在外部定义变量访问闭包:

def outer_function(x):
    def inner_function(y):
        return x + y
    return inner_function

add_five = outer_function(5)
print(add_five(10))  # 输出 15
python

对于更复杂的嵌套闭包:

def create_adder(x):
    def addend1(y):
        def addend2(z):
            return x + y + z
        return addend2
    return addend1

add_five = create_adder(5)
add_five_and_ten = add_five(10)
print(add_five_and_ten(15))  # 输出 30
python

闭包的两个作用,“读取函数内部的变量”和“让函数内部的局部变量始终保持在内存中”,都能通过类的实例变量来实现。但是对于对象的方法较少的情况,使用闭包会更简洁。

注意事项#

返回闭包时,返回函数不要引用任何循环变量,或者后续会发生变化的变量,否则会导致返回的闭包引用的是变量的最后一个值:

def count():
    fs = []
    for i in range(1, 4):
        def f():
             return i*i
        fs.append(f)
    return fs

f1, f2, f3 = count()
# 实际上都返回了9
python

nonlocal 关键字 在闭包中,如果需要修改外部函数的变量,可以使用 nonlocal 关键字:

def make_counter():
    count = 0
    def counter():
        nonlocal count
        count += 1
        return count
    return counter

counter = make_counter()
print(counter())  # 输出 1
print(counter())  # 输出 2
python

参考资料#

  1. Python闭包详解:从函数式编程到实际应用
  2. Python闭包(Closure)详解
  3. 深入浅出python闭包
©
Python学习笔记:闭包机制 (Closure)
https://astro-pure.js.org/blog/technology/python-notes/closure
Author Rinne
Published at 2025年11月5日
Comment seems to stuck. Try to refresh?✨