Python 闭包 (Closure)
大家好!今天我们来聊聊Python的闭包Closure。 闭包是指函数记住了外部作用域的变量,即使 外部函数已执行完毕。这使得函数可以访问其 创建时的环境。
在这个例子中,multiplier_factory返回了 multiplier函数,它记住了m的值。double和 triple是不同的闭包, 有不同的m值。
在counter例子中,increment函数使用了
nonlocal
关键字。这是因为我们需要修改
外部函数counter中的count变量。如果没有
nonlocal
,increment会创建一个新的局部
变量count,而不是修改外部的count。
关于闭包的垃圾回收,闭包的函数在不再被引用时会被垃圾回收。
在我们的例子中,my_counter
变量引用了
counter
函数返回的increment
闭包。只要
my_counter
存在,increment
闭包就不会
被垃圾回收。只有当my_counter
不再被引用
时,例如被赋值为None
,闭包才会被回收。
通常情况下,Python的垃圾回收机制会自动
处理,无需手动设置为None
,除非你需要
立即释放内存。
闭包的用途包括:数据隐藏、创建函数工厂等。 它们可以帮助编写更灵活和可维护的代码。 希望这个简单的例子能帮助你理解Python的Closure!
代码示例
def multiplier_factory(m):
def multiplier(x):
return x * m
return multiplier
double = multiplier_factory(2)
triple = multiplier_factory(3)
print(double(5))
print(triple(5))
def counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
my_counter = counter()
print(my_counter())
print(my_counter())