什么是Python 闭包
发布时间:2023-06-27 10:40:17 所属栏目:教程 来源:
导读:闭包是较难理解的概念,Python 初学者可以暂时跳过此节。学习此节时需要理解 “函数是第一类对象” 的概念,在词条 “Python 的 lambda 表达式” 中详细介绍了这一概念。
本节首先讲解理解闭
本节首先讲解理解闭
闭包是较难理解的概念,Python 初学者可以暂时跳过此节。学习此节时需要理解 “函数是第一类对象” 的概念,在词条 “Python 的 lambda 表达式” 中详细介绍了这一概念。 本节首先讲解理解闭包所需要的铺垫知识,最后再引入闭包的定义。 1. 嵌套定义函数 1.1 在函数内部定义函数 Python 允许嵌套定义函数,可以在函数中定义函数,例如: def outter():def inner():print('Inside inner')print('Inside outter')inner()outter() 在第 1 行,定义函数 outter 在第 2 行,在函数 outter 内部,定义函数 inner 在第 6 行,在函数 outter 内部,调用函数 inner 函数 inner 定义在函数 outter 中,被称为函数嵌套定义。运行程序,输出结果如下: Inside outter Inside inner 1.2 实现信息隐藏 定义在函数内部的函数,对外是不可见的,例如: def outter():def inner():print('inside inner')print('inside outter') inner()inner() 在第 1 行,定义了外部函数 outter 在第 2 行,定义了内部函数 inner 在第 6 行,在函数 outter 中,调用函数 inner 在第 8 行,调用函数 inner 程序运行,输出如下: Traceback (most recent call last): File visible.py, line 8, in <module>inner()NameError: name 'inner' is not defined 在第 4 行,试图调用定义在函数 outter 内部定义的函数 inner,程序运行时报错:name ‘inner’ is not defined,即找不到函数 inner。 因为函数 inner 是定义在函数 outter 内部的,函数 inner 对外部是不可见的,因此函数 outter 向外界隐藏了实现细节 inner,被称为信息隐藏。 1.3 实现信息隐藏的例子 实现一个复杂功能的函数时,在函数内部定义大量的辅助函数,这些辅助函数对外不可见。例如,假设要实现一个函数 complex,函数的功能非常复杂,将函数 complex 的功能分解为 3 个子功能,使用三个辅助函数 f1、f2、f3 完成对应的子功能,代码如下: def f1():print('Inside f1')def f2():print('Inside f2')def f3():print('Inside f3')def complex():print('Inside complex')f1()f2()f3() 在第 1 行,定义了辅助函数 f1 在第 4 行,定义了辅助函数 f2 在第 7 行,定义了辅助函数 f3 在第 10 行,定义了主函数 complex,它通过调用 f1、f2、f3 实现自己的功能 在以上的实现中,函数 f1、f2、f3 是用于实现 complex 的辅助函数,我们希望它们仅仅能够被 complex 调用,而不会被其它函数调用。如果可以将函数 f1、f2、f3 定义在函数 complex 的内部,如下所示: def complex():def f1():print('Inside f1')def f2():print('Inside f2')def f3():print('Inside f3')print('Inside complex')f1()f2()f3() 在第 2 行,在函数 complex 内部定义函数 f1 在第 4 行,在函数 complex 内部定义函数 f2 在第 6 行,在函数 complex 内部定义函数 f3 在第 10 行到第 12 行,调用 f1、f2、f3 实现函数 complex 的功能 2. 内部函数访问外部函数的局部变量 嵌套定义函数时,内部函数可能需要访问外部函数的变量,例子代码如下: def outter():local = def inner(local):print('Inside inner, local = %d', local)inner(local)outter() 在第 1 行,定义了外部函数 outter 在第 2 行,定义了函数 outter 的局部变量 local 在第 4 行,定义了内部函数 inner 函数 inner 需要访问函数 outter 的局部变量 local 在第 7 行,将函数 outter 的局部变量 local 作为参数传递给函数 inner 在第 5 行,函数 inner 就可以访问函数 outter 的局部变量 local 程序运行结果如下: Inside inner, local = 123 在上面的例子中,将外部函数 outter 的局部变量 local 作为参数传递给内部函数 inner。Python 允许内部函数 inner 不通过参数传递直接访问外部函数 outter 的局部变量,简化了参数传递,代码如下: def outter():local = def inner():print('Inside inner, local = %d', local)inner() 在第 1 行,定义了外部函数 outter 在第 2 行,定义了函数 outter 的局部变量 local 在第 4 行,定义了内部函数 inner 函数 inner 需要访问函数 outter 的局部变量 local 在第 5 行,函数 inner 可以直接访问函数 outter 的局部变量 local 在第 7 行,不用传递参数,直接调用函数 inner() (编辑:汽车网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |