今天看了知乎@蕭井陌的編程入門指南,想重溫一下 《python簡明教程》,對global的用法一直不太熟練,在此熟練一下,並實踐一下python中list、tuple、set作為參數的區別。
在函數內部定義變量時,他們與函數外部具有相同名稱的其他變量沒有任何關系,即變量名稱對於函數來說是局部的,這稱為變量的作用域,示例如下:
def func_local(x): print 'x is', x x = 2 print 'Chanaged local x to',x x = 50 func_local(x) print 'x is still', x
執行結果:
x is 50 Chanaged local x to 2 x is still 50
如果想在函數內部改變函數外的變量值,用global語句完成

def func_global(): global y print 'y is', y y = 50 print 'Changed local y to', y y = 10 func_global() print 'Value of y is', y
執行結果:

y is 10 Changed local y to 50 Value of y is 50
函數參數若是list、set、dict可變參數,在函數內改變參數,會導致該參數發生變化,例如:

def func_local(x): print 'x is', x x.append(10) print 'Chanaged local x to',x x = range(6) func_local(x) print 'x is', x
執行結果

x is [0, 1, 2, 3, 4, 5] Chanaged local x to [0, 1, 2, 3, 4, 5, 10] x is [0, 1, 2, 3, 4, 5, 10]

def func_local(x): print 'x is', x x.add(10) print 'Chanaged local x to',x x = set(range(6)) func_local(x) print 'x is', x
執行結果:

x is set([0, 1, 2, 3, 4, 5]) Chanaged local x to set([0, 1, 2, 3, 4, 5, 10]) x is set([0, 1, 2, 3, 4, 5, 10])

def func_local(x): print 'x is', x x['x'] = 2 print 'Chanaged local x to',x x = dict([('x',1), ('y', 2)]) func_local(x) print 'x is', x
執行結果:

x is {'y': 2, 'x': 1} Chanaged local x to {'y': 2, 'x': 2} x is {'y': 2, 'x': 2}

def func_local(x): print 'x is', x x = (4, 5, 6) print 'Chanaged local x to',x x = (1,2,3,) func_local(x) print 'x is', x
執行結果

x is (1, 2, 3) Chanaged local x to (4, 5, 6) x is (1, 2, 3)
若傳入可變參數如list、set、dict,在函數內部對參數做出修改,參數本身發生變化,tuple、str不變