歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python3.X增加的關鍵字nonlocal

Python3.X增加的關鍵字nonlocal

日期:2017/3/1 10:24:17   编辑:Linux編程
全局變量和別名
Python裡只有2種作用域:全局作用域和局部作用域。全局作用域是指當前代碼所在模塊的作用域,局部作用域是指當前函數或方法所在的作用域。其實准確來說,Python 3.x引入了nonlocal關鍵字,可以用於標識外部作用域的變量。

局部作用域裡的代碼可以讀外部作用域(包括全局作用域)裡的變量,但不能更改它。一旦進行更改,就會將其當成是局部變量。而如果在更改前又進行了讀取操作,則會拋出異常。

  1. def f():
  2. x = '1'
  3. def g():
  4. x += '2'
  5. return x
  6. return g
  7. print f()()
如果要更改外部作用域裡的變量,最簡單的辦法就是將其放入全局作用域,用global關鍵字引入該變量。
  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中,閉包只能讀外部函數的變量,而不能改寫它。
  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. a()()
如果要對x進行賦值操作,在Python 2.x中解決這個問題,目前只能使用全局變量:global
為了解決這個問題,Python 3.x引入了nonlocal關鍵字(詳見The nonlocal statement)。
只要在閉包內用nonlocal聲明變量,就可以讓解釋器在外層函數中查找變量名了
  1. def a():
  2. x = 0
  3. def b():
  4. nonlocal x
  5. x += 1
  6. print x
  7. return b
  8. a()()
Copyright © Linux教程網 All Rights Reserved