Contents

全域變數與區域變數

全域變數(Global)

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

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

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

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

1
2
3
4
GV = 10

def function():
	GV += 10

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

1
2
3
def function():
	global GA
	GA = 10

區域變數(Nonlocal)

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

1
2
3
4
5
6
7
8
def fun():
	def fun2():
		print(g)
		#g += 10
		#UnboundLocalError

	g = 10
	fun2()

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

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

	g = 10
	fun2()