python nonlocal/global ---內部作用域中改變外部變量

nonlocal,作用:使外層函數中的變量能被內層函數中被查找到,使用,或更改。
global,作用:在外層函數中使用和改變全局變量

原因:在python中,局部作用域裏面的代碼可以讀取外部作用域(包括全局作用域)的變量,但是規定一般情況不能更改外部作用域的變量的值。一旦更改,會報錯。爲改變這種狀態,引入關鍵字:nonlocal。
例如:
1.用全局變量,在內層函數中修改值,不使用nonlocal

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
x=2                 #全局變量
def func_outer():   #外層函數                   
    print (x)       #只調用全局變量,不改變其值
    def func_inner():   #內層函數     
        x=x+1           #改變全局變量,不使用nonlocal    
        print(x)
    func_inner()
func_outer()
#結果:報錯:x---局部變量沒有被定義就使用

2.內層函數使用、改變外層函數變量,不使用nonlocal

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def func_outer():                 #外層函數 
    x=2                      #建立一個變量       
    print (x)
    def func_inner():        #內層函數
        x=x+1               #改變外層函數變量
        print(x)
    func_inner()
func_outer()
#結果:局部變量沒有被定義就使用

在定義局部變量前在函數中使用局部變量(此時有與局部變量同名的全局變量存在)
(導致“UnboundLocalError: local variable ‘foobar’ referenced before assignment”)

3.外層函數改變全局變量,不使用:global

x=0
def func_outer():
    x+=1
    print("change x ",x)
func_outer()
#結果:UnboundLocalError: local variable 'x' referenced before assignment

4.使用,改變外部變量,使用nonlocal

def func_outer():
    x=2                                              #外層函數
    def func_inner():
        nonlocal x                               #使用nonlocal 使用外層函數的變量
        x=x+1
        print(x)
    func_inner()
    print("change x ",x)
func_outer()
#結果:
3
change x  3

5.使用,改變全局變量,使用golobal


x=0
def func_outer():                                                #外層函數
    global x
    x+=1
    def func_inner():
        #nonlocal x                               #使用nonlocal 使用外層函數的變量
        #x=x+1
        print(x)
    func_inner()
    print("change x ",x)
func_outer()
#結果:
1
change x  1

5.在外部函數和內部函數同時改變全局變量

x=0
def func_outer():                                                #外層函數
    global x
    x+=1
    def func_inner(x):
        #nonlocal x                  #使用nonlocal會報錯
        x=x+1
        print('內層函數',x)
    func_inner(x)
    print("外層函數",x)
func_outer()
print('全局變量',x)
#結果:
內層函數 2
外層函數 1
全局變量 1
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章