闭包(Closure)是Python中的一个重要概念,它允许一个函数记住并访问其外部作用域中的变量,即使外部函数已经执行完毕。在Python中,闭包可以通过以下几种方式实现:
嵌套函数:
在外部函数中定义一个内部函数,内部函数引用外部函数的局部变量。
def outer_function(x):
def inner_function(y):
return x + y
return inner_function
closure = outer_function(10)
print(closure(5)) 输出 15
使用`nonlocal`关键字:
在内部函数中使用`nonlocal`关键字声明要修改的外部函数的变量。
def outer(x):
count =
def inner():
nonlocal count
count += 1
return count
return inner
hello = outer()
print(hello()) 输出 1
print(hello()) 输出 2
使用`global`关键字:
在内部函数中使用`global`关键字声明要引用的全局变量。
origin = 0
def news(steps):
global origin
new = origin + steps
origin = new
return new
print(news(2)) 输出 2
print(news(7)) 输出 9
返回函数:
外部函数返回内部函数,从而形成闭包。
def count():
fs = []
for i in range(1, 4):
def f(j):
def g():
return j * j
return g
fs.append(f(i))
return fs
f1, f2, f3 = count()
print(f1()) 输出 1
print(f2()) 输出 4
print(f3()) 输出 9
闭包在Python中非常有用,它们可以用于实现装饰器、创建只读属性、实现轻量级匿名类等。需要注意的是,闭包可能会导致内存泄漏,因为引用的外部变量不会被垃圾回收,所以应当谨慎使用。