python nonlocal关键字

来源:互联网 发布:java使用md5加密解密 编辑:程序博客网 时间:2024/06/05 09:08
全局变量和别名
Python里只有2种作用域:全局作用域和局部作用域。全局作用域是指当前代码所在模块的作用域,局部作用域是指当前函数或方法所在的作用域。其实准确来说,Python 3.x引入了nonlocal关键字,可以用于标识外部作用域的变量。

局部作用域里的代码可以读外部作用域(包括全局作用域)里的变量,但不能更改它。一旦进行更改,就会将其当成是局部变量。而如果在更改前又进行了读取操作,则会抛出异常。

[python] view plain copy
 
 
  1. def f():  
  2.   x = '1'  
  3.   def g():  
  4.     x += '2'  
  5.     return x  
  6.   return g  
  7. print f()()  
如果要更改外部作用域里的变量,最简单的办法就是将其放入全局作用域,用global关键字引入该变量。

[python] view plain copy
 
 
  1. x = ''  
  2. def f():  
  3.   global x  
  4.   x = '1'  
  5.   def g():  
  6.     global x  
  7.     x += '2'  
  8.     return x  
  9.   return g  
  10. print f()()  
在Python 2.x中,闭包只能读外部函数的变量,而不能改写它。

[python] view plain copy
 
 
  1. def a():  
  2.   x = 0  
  3.   def b():  
  4.     print locals()  
  5.     y = x + 1  
  6.     print locals()  
  7.     print x, y  
  8.   return b  
  9.   
  10. a()()  
如果要对x进行赋值操作,在Python 2.x中解决这个问题,目前只能使用全局变量:global
为了解决这个问题,Python 3.x引入了nonlocal关键字(详见The nonlocal statement)。
只要在闭包内用nonlocal声明变量,就可以让解释器在外层函数中查找变量名了

[python] view plain copy
 
 
  1. def a():  
  2.   x = 0  
  3.   def b():  
  4.     nonlocal x  
  5.     x += 1  
  6.     print x  
  7.   return b  
  8.   
  9. a()()