看別人寫的程序在方法里面的變量前加了global關鍵字,之前沒接觸過,遂學習記錄下這個知識點
- 變量作用域
先要明確作用域的概念,定義在函數內部的變量擁有一個局部作用域,而定義在函數外的擁有全局作用域。
a = 5 # 這是一個全局變量
def hello():
a = 1 # a在這里是局部變量.
print("函數內是局部變量 : ", a)
return a
hello()
print("函數外是全局變量 : ", a)
運行結果
函數內是局部變量 : 1
函數外是全局變量 : 5
- global關鍵字
如果想要在函數內部用模塊定義的變量的話,就需要用到global關鍵字
a = 5
def hello():
global a
# 聲明告訴執行引擎用的是全局變量a
a = 1
print('In test func: a = %d' % a)
hello()
print('Global a = %d' % a)
運行結果:
In test func: a = 1
Global a = 1
可以看到函數里成功修改了全局變量a
參考資料
https://blog.csdn.net/diaoxuesong/article/details/42552943
http://www.runoob.com/python/python-functions.html