Python nonlocal 與 global 關鍵字解析


nonlocal

首先,要明確 nonlocal 關鍵字是定義在閉包里面的。請看以下代碼:

x = 0
def outer():
    x = 1
    def inner():
        x = 2
        print("inner:", x)

    inner()
    print("outer:", x)

outer()
print("global:", x)

結果

# inner: 2
# outer: 1
# global: 0

現在,在閉包里面加入nonlocal關鍵字進行聲明:

x = 0
def outer():
    x = 1
    def inner():
		nonlocal x
        x = 2
        print("inner:", x)

    inner()
    print("outer:", x)

outer()
print("global:", x)

結果

# inner: 2
# outer: 2
# global: 0

看到區別了么?這是一個函數里面再嵌套了一個函數。當使用 nonlocal 時,就聲明了該變量不只在嵌套函數inner()里面
才有效, 而是在整個大函數里面都有效。

global

還是一樣,看一個例子:

x = 0
def outer():
    x = 1
    def inner():
        global x
        x = 2
        print("inner:", x)

    inner()
    print("outer:", x)

outer()
print("global:", x)

結果

# inner: 2
# outer: 1
# global: 2

global 是對整個環境下的變量起作用,而不是對函數類的變量起作用。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM