ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、视频、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
闭包 ---- 闭包:返回函数中,内函数调用了外函数的临时变量,即构成闭包。 特点 ----- - 外函数把外部变量绑定给内函数 外部变量都有:外函数参数、外函数作用域内变量 - 每次调用外函数,都会创建并返回一个新的的内函数,且给内函数绑定新的局部变量 修改外函数中的局部变量 -------------------------- 1) 使用可变对象作为局部变量 2) 使用 nonlocal ~~~ def outer(a): b = 10 c = [] def inner(): nonlocal b b += 1 c.append(1) return b, c return inner demo = outer(1) print(demo()) # (11, [1]) print(demo()) # (12, [1, 1]) ~~~ 练习 ----- 利用闭包返回一个计数器函数,每次调用它返回递增整数 ~~~ def count(step=1): n = 0 def inner(): nonlocal n n += step return n return inner cnt = count() print(cnt()) print(cnt()) print(cnt()) ~~~