Python global 全域變數用法與範例

本篇介紹 Python global 全域變數用法與範例,Python 全域變數要使用 global 這個關鍵字,先來說說區域變數與全域變數的差別,區域變數(local variable)是該變數只有在函式內使用,影響範圍也只在這函式內,離開這個函式時該變數的生命週期也就結束;全域變數(global variable)是該變數可以在整個程式內使用,影響範圍也在這個程式內,一直到結束這個程式時該變數的生命週期才結束。

以下的 Python global 全域變數用法與範例將分為這幾部分,

  • Python 區域變數與全域變數的差別
  • Python 在函式裡宣告全域變數

那我們開始吧!

Python 區域變數與全域變數的差別

這邊介紹 Python 區域變數與全域變數的差別,如下範例所示,在程式裡的 s 是全域變數,呼叫 myprint 要印出 s 時,因為區域變數裡沒有 s,所以會印出全域變數的 s,

1
2
3
4
5
6
def myprint():
print('myprint: ' + s)

s = 'I am global variable'
print(s)
myprint()

結果如下,

1
2
I am global variable
myprint: I am global variable

那如果我們在 myprint 裡加入 s 這個區域變數呢?

1
2
3
4
5
6
7
def myprint():
s = 'I am local variable'
print('myprint: ' + s)

s = 'I am global variable'
print(s)
myprint()

結果如下,結果是 myprint 就會印出區域變數的 s,

1
2
I am global variable
myprint: I am local variable

不過實際上我們通常不會將區域變數取的名子跟全域變數一樣,因為這可能會造成混淆跟誤會。

Python 在函式裡宣告全域變數

這邊介紹 Python 如何在函式裡宣告全域變數,只要在函式裡使用 global 這個關鍵字來宣告變數,這樣 Python 直譯器就會知道該變數是全域變數,用法範例如下,

1
2
3
4
5
6
7
def myprint():
global s
s = 'hello world'
print('myprint: ' + s)

myprint()
print(s)

這樣 myprint 函式結束後都還能存取 s 全域變數,結果如下,

1
2
myprint: hello world
hello world

再舉一個計數器的例子,並且在一開始時將 counter 設定為 0,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
counter = 0
def func_a():
global counter
counter += 2
print('func_a counter: ' + str(counter))

def func_b():
global counter
counter += 3
print('func_b counter: ' + str(counter))

func_a()
print('counter: ' + str(counter))
func_b()
print('counter: ' + str(counter))

經過 func_a 與 func_b 執行後都有修改到全域變數的 counter,結果如下,

1
2
3
4
func_a counter: 2
counter: 2
func_b counter: 5
counter: 5

以上就是 Python global 全域變數用法與範例介紹,
如果你覺得我的文章寫得不錯、對你有幫助的話記得 Facebook 按讚支持一下!

其它相關文章推薦
Python 新手入門教學懶人包
Python 讀取 txt 文字檔
Python 寫檔,寫入 txt 文字檔
Python 讀取 csv 檔案
Python 寫入 csv 檔案
Python 讀寫檔案
Python 產生 random 隨機不重複的數字 list
Python PyAutoGUI 使用教學
Python OpenCV resize 圖片縮放