闭包函数
闭包函数:内部函数(包含)对外部作用域而非全剧作用域变量的引用,该内部函数(函数内部定义的函数称为内部函数)称为闭包函数
闭包只存在于内层函数中。
函数都要逐层返回,最终返回给最外层函数。
由于有了作用域的关系,我们就不能拿到函数内部的变量和函数了。如果我们就是想拿怎么办呢?返回呀!
我们都知道函数内的变量我们要想在函数外部用,可以直接返回这个变量,那么如果我们想在函数外部调用函数内部的函数呢?直接就把这个内部函数的名字返回
一下是闭包函数最常用的用法
def func(): name='python' def inner(): print(name) return inner f=func() f()
结果为:python
1 判断是否是闭包函数
f.__closure__[0].cell_contents
如果有返回值,则说明是闭包函数,如果不是闭包函数会报错。
1.1 获取闭包引用的外层变量
def func(): name = 'python' author='龟叔' def inner(): print(name) print(author) return inner f = func()
# 获取闭包引用的外层变量
print(f.__closure__[0].cell_contents) print(f.__closure__[1].cell_contents)
结果为:
龟叔
python
1.2 不是闭包的示例
name = 'alex' def func(): def inner(): print(name) return inner f = func() print(f.__closure__[0].cell_contents)
运行会报错
Traceback (most recent call last): File "E:/python/test10.py", line 14, in <module> print(f.__closure__[0].cell_contents) TypeError: 'NoneType' object is not subscriptable
2 闭包的应用:
解释器执行程序时,如果遇到函数,随着函数的结束而关闭临时名称空间,
但是 如果遇到闭包,有一个机制:那么闭包的空间不会随着函数的结束而关闭。
# 1,装饰器。
# 2,爬虫。
def wrapper(step): num = 1 def inner(): nonlocal num num += step print(num) return inner f = wrapper(3) j = 0 while j < 5: f() # inner() j += 1
结果为:
4 7 10 13 16

浙公网安备 33010602011771号