闭包是一类特殊类型的函数,如果一个函数定义在另一个函数的作用域中,并且函数中引用了外部函数的局部变量,那么这个函数就是一个闭包。
def f(): n = 1 def inner(): print n inner() n = 'x' inner()如果需要在函数中修改全局变量,可以使用关键字global修饰变量名。Python 2.x中没有关键字为在闭包中修改外部变量提供支持,在3.x中,关键字nonlocal可以做到这一点:
#Python 3.x supports `nonlocal'def f(): n = 1 def inner(): nonlocal n n = 'x' print(n) inner() print(n)
浙公网安备 33010602011771号