程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python tutorial: difference and usage of global and nonlocal keywords

編輯:Python

一:global:referenced inside the function/聲明全局變量

在自定義函數時,Sometimes it is necessary to refer to some global variables outside the function,If you do not need to modify the contents of the global variable,則可以直接引用,像下面這樣:

c = 999
def func():
print(c)
if __name__ == '__main__':
func()

What the function does is just output the variable c 的值,並未對 c 進行修改,所以不會報錯.But if you want to make a modification to the global variable inside the function,則需要使用global關鍵字,

c = 999
def func():
for i in range(10):
c += 1
if __name__ == '__main__':
func()
print(c).

上面的代碼中,在func函數中嘗試修改 c 這個變量,But the following error occurs:

UnboundLocalError: local variable ‘c’ referenced before assignment

意思是:A local variable is referenced before assignment.global關鍵字可以解決這個問題,如下:

c = 999
def func():
global c # Use before modificationglobal關鍵字
for i in range(10):
c += 1
if __name__ == '__main__':
func()
print(c)

另外,globalIt also helps us to declare a global variable inside the function,如下:

def func():
global c # 在函數內部聲明一個全局變量
c = 100
if __name__ == '__main__':
func()
print(c)

二:nonlocal關鍵字

nonlocal的作用於global類似,只不過globalis referenced inside the function/修改全局變量,而nonlocais referenced in the inner function/Modify the local variables defined by the outer function(非全局變量).This phenomenon also becomes a closure.

def func():
c = 100
def foo():
for i in range(10): # to the outer functionc變量進行修改
c += 1
foo()
print(c)
if __name__ == '__main__':
func()

報錯如下:

UnboundLocalError: local variable 'c' referenced before assignment

Same error as above,But this time can no longer be usedglobal關鍵字了,而要使用nonlocal關鍵字,(如果使用了global,It is equivalent to declaring a new variable again)

''' 學習中遇到問題沒人解答?小編創建了一個Python學習交流群:711312441 尋找有志同道合的小伙伴,互幫互助,群裡還有不錯的視頻學習教程和PDF電子書! '''
def func():
c = 100
def foo():
nonlocal c
for i in range(10): # to the outer functionc變量進行修改
c += 1
foo()
print(c)
if __name__ == '__main__':
func()

這樣就不會報錯了,輸出結果是110.

總的來說:globalKeywords are used to use global variables in functions or other local scopes.But it doesn't apply if you don't use global variablesglobal關鍵字聲明,nonlocalThe keyword is used to use the outer layer in a function or other scope(非全局)變量.


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved