標籤:若是 cal bsp 變化 關係 oba hang bar aced
在函數內部定義變數時,他們與函數外部具有相同名稱的其他變數沒有任何關係,即變數名稱對於函數來說是局部的,這稱為變數的範圍,樣本如下:
def func_local(x): print ‘x is‘, x x = 2 print ‘Chanaged local x to‘,xx = 50func_local(x)print ‘x is still‘, x
執行結果:
x is 50Chanaged local x to 2x is still 50
如果想在函數內部改變函數外的變數值,用global陳述式完成
def func_global(): global y print ‘y is‘, y y = 50 print ‘Changed local y to‘, yy = 10func_global()print ‘Value of y is‘, y
def func_global(): global y print ‘y is‘, y y = 50 print ‘Changed local y to‘, yy = 10func_global()print ‘Value of y is‘, y
執行結果:
y is 10Changed local y to 50Value of y is 50
y is 10Changed local y to 50Value of y is 50
函數參數若是list、set、dict可變參數,在函數內改變參數,會導致該參數發生變化,例如:
def func_local(x): print ‘x is‘, x x.append(10) print ‘Chanaged local x to‘,xx = range(6)func_local(x)print ‘x is‘, x
def func_local(x): print ‘x is‘, x x.append(10) print ‘Chanaged local x to‘,xx = 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]
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‘,xx = set(range(6))func_local(x)print ‘x is‘, x
def func_local(x): print ‘x is‘, x x.add(10) print ‘Chanaged local x to‘,xx = 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])
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‘,xx = dict([(‘x‘,1), (‘y‘, 2)])func_local(x)print ‘x is‘, x
def func_local(x): print ‘x is‘, x x[‘x‘] = 2 print ‘Chanaged local x to‘,xx = 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}
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‘,xx = (1,2,3,)func_local(x)print ‘x is‘, x
def func_local(x): print ‘x is‘, x x = (4, 5, 6) print ‘Chanaged local x to‘,xx = (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)
x is (1, 2, 3)Chanaged local x to (4, 5, 6)x is (1, 2, 3)
若傳入可變參數如list、set、dict,在函數內部對參數做出修改,參數本身發生變化,tuple、str不變
python-global全域變數