Contents

全域變數與區域變數

全域變數

一般情況下,全域變數(Global Variable)可被function、class獲取,但不可修改。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#這是一個全域變數
GV = 10

def function():
	print(GV)
	GA += 10

function()
#>>>10
#>>>UnboundLocalError

使用global後,全域變數才可被修改。

1
2
3
4
5
6
7
8
9
GV = 10

def function():
    global GV
    GV += 10
    print(GV)

function()
#>>>20

假使global的全域變數對象不存在,則會建立一新的全域變數。

1
2
3
4
5
6
7
8
def function():
    global GV
    GV = 10
    GV += 10  

function()
print(GV)
#>>>20

區域變數

區域變數(Local Variable)與全域變數情況相同,可被下一層(或下幾層)獲取,但不可修改。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def fun():
    def fun2():
        print(g)

    def fun3():
        g += 10

    g = 10
    fun2()
    fun3()

fun()
#>>>10
#>>>UnboundLocalError

使用nonlocal後,區域變數才可被修改。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def fun():
    def fun2():
        nonlocal g
        g += 10
        print(g)  

    g = 10
    fun2()

fun()
#>>>20

小結

總而言之,無論是全域變數或區域變數,皆只能被下級層獲取,無法修改(相反來說,上層則永遠也無法獲取下層的變數)。若要修改必須使用globalnonlocal,但還是建議在設計程式之初就安排好變數間的層級關係,避免過度跨越層級調用才能編寫出可讀、可維護的code。