1.  
  2. 主页
  3.  / 
  4. Python基础到高级
  5.  / 
  6. 函数
  7.  / 
  8. 闭包

闭包

闭包

函数已经结束,但是函数内部变量的引用还存在,Python的闭包可以使用可变的容器实现,这是Python2的唯一方式

>>> def counter():   Python闭包结构
...     c = [0]
...     def inc():
...         c[0] += 1
...         return c[0]
...     return inc
... 
>>> f = counter()
>>> f()
1
>>> f()
2

Python3中是有其他的实现方式的,nonlocal关键字来实现闭包

>>> def counter():
...     x = 0
...     def inc():  
...         nonlocal x   nonlocal关键字用于标记一个变量由他的上级作用域定义,通过nonlocal标记的变量,可读可写
...         x += 1
...         return x
...     return inc
... 
>>> f = counter()
>>> f()
1
>>> f()
2
>>> f()
3

>>> def fn():  
...     nonlocal xxxx   因为nonlocal是直接指定上级作用域中的变量,因此,若是上级作用域中没有定义该变量,那么机会抛出语法错误
... 
  File "<stdin>", line 2
SyntaxError: no binding for nonlocal 'xxxx' found
这篇文章对您有用吗? 1

我们要如何帮助您?

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注