日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python?nonlocal關鍵字?與?global?關鍵字解析_python

作者:Brad1994 ? 更新時間: 2022-05-27 編程語言

python引用變量的順序: 當前作用域局部變量->外層作用域變量->當前模塊中的全局變量->python內置變量

1.nonlocal

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()里面才有效, 而是在整個大函數里面都有效。

2.global

global關鍵字用來在函數或其他局部作用域中使用全局變量。但是如果不修改全局變量也可以不使用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 是對整個環境下的變量起作用,而不是對函數類的變量起作用。

原文鏈接:https://www.cnblogs.com/brad1994/p/6533267.html

欄目分類
最近更新