Python3 【闭包】避坑指南:常见错误解析
闭包是Python中一个强大的特性,但在使用过程中容易遇到一些常见的错误。以下是 10 个常见的闭包错误、错误原因分析以及纠错方法。
1. 忘记使用 nonlocal
关键字
错误代码:
def outer():
x = 10
def inner():
x += 1 # 错误:未声明 x 为 nonlocal
return x
return inner
f = outer()
print(f()) # 报错:UnboundLocalError
错误原因:
在内部函数中修改外部函数的变量时,必须使用 nonlocal
关键字声明,否则 Python 会将其视为局部变量。
纠错方法:
使用 nonlocal
声明变量。
def outer():
x = 10
def inner():
nonlocal x # 声明 x 为外部变量
x += 1
return x
return inner
f = outer()
print(f()) # 输出: 11
2. 误用可变对象
错误代码:
def outer():
lst = []
def inner():
lst.append(1) # 修改了外部变量
return lst
return inner
f = outer()
print(f()) # 输出: [1]
print(f()) # 输出: [1, 1] (可能不符合预期)
错误原因:
如果闭包修改了外部函数的可变对象(如列表),可能会导致意外的副作用。
纠错方法:
避免直接修改外部变量,或者明确设计意图。
def outer():
lst = []
def inner():
new_lst = lst.copy() # 创建副本以避免副作用
new_lst.append(1)
return new_lst
return inner
f = outer()
print(f()) # 输出: [1]
print(f()) # 输出: [1]