Python - 闭包


在本章中,我们将讨论Python中闭包的概念。在 Python 中,函数被称为一阶对象。就像主要数据类型一样,函数也可以用于分配给变量,或作为参数传递。

嵌套函数

您还可以有函数的嵌套声明,其中一个函数是在另一个函数体内定义的。

例子

def functionA(): print ("Outer function") def functionB(): print ("Inner function") functionB() functionA()

它将产生以下输出-

Outer function
Inner function

在上面的例子中,functionB是在functionA内部定义的。然后从外部函数的作用域内部调用内部函数。

如果外部函数接收任何参数,则可以将其传递给内部函数。

def functionA(name): print ("Outer function") def functionB(): print ("Inner function") print ("Hi {}".format(name)) functionB() functionA("Python")

它将产生以下输出 -

Outer function
Inner function
Hi Python

什么是闭包?

闭包是一个嵌套函数,它可以从已完成执行的封闭函数中访问变量。这样的变量未绑定在局部范围内。要使用不可变变量(数字或字符串),我们必须使用 nonlocal 关键字。

Python 闭包的主要优点是我们可以帮助避免使用全局值并提供某种形式的数据隐藏。它们用于 Python 装饰器。

例子

def functionA(name): name ="New name" def functionB(): print (name) return functionB myfunction = functionA("My name") myfunction()

它将产生以下输出-

New name

在上面的例子中,我们有一个 functionA 函数,它创建并返回另一个函数 functionB。嵌套的 functionB 函数就是闭包。

外部 functionA 函数返回一个 functionB 函数并将其分配给 myfunction 变量。即使它已经完成了执行。然而,打印机闭包仍然可以访问 name 变量。

非本地关键字

在Python中,nonlocal关键字允许访问本地范围之外的变量。这在闭包中用于修改外部变量范围中存在的不可变变量。

例子

def functionA(): counter =0 def functionB(): nonlocal counter counter+=1 return counter return functionB myfunction = functionA() retval = myfunction() print ("Counter:", retval) retval = myfunction() print ("Counter:", retval) retval = myfunction() print ("Counter:", retval)

它将产生以下输出-

Counter: 1
Counter: 2
Counter: 3