聲明: 這篇文章很大程度上借鑑了 Global, Local and nonlocal Variables。
local
變量與其它的編程語言相同,在函數中聲明的變量都是local
變量。做用域僅限於函數中,從函數外是訪問不到的。php
In [1]: def f(): s = 'local val' print('read s from interval:', s) In [2]: print(s) NameError: name 's' is not defined In [3]: f() read s from interval: local val
global
變量在源文件中(非函數或類)聲明的變量默認是global
變量。python
global
變量,這一點很少說,不論是函數聲明在前,仍是global
變量聲明在前global
變量的時候,要特別注意了: 若是在函數體中未使用global
聲明這個變量,那麼函數體中修改的是local
變量的值,global
變量並未更新。In [4]: s = 'global val' In [6]: def f(): ...: s = 'change global val' ...: print('change global val', s) ...: In [7]: f() change global val change global val In [8]: s Out[8]: 'global val'
正確的作法應該是:編程
In [4]: s = 'global val' In [6]: def f(): ...: global s ...: s = 'change global val' ...: print('change global val', s) ...: In [7]: f() change global val change global val In [8]: s Out[8]: 'change global val change global val'
nonlocal
變量nonlocal
是python3
引入的,只能用於嵌套函數中。在嵌套函數中使用nonlocal
聲明變量,能夠修改外層函數中的變量。編程語言
In [11]: def outer(): ...: s = 'outer val' ...: def inner(): ...: nonlocal s ...: s = 'inner val' ...: print('change outer s',s) ...: print('before inner(), s=', s) ...: inner() ...: print('after inner(), s=', s) ...: In [12]: outer() before inner(), s= outer val change outer s inner val after inner(), s= inner val