python-global全局变量
生活随笔
收集整理的這篇文章主要介紹了
python-global全局变量
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在函數內部定義變量時,他們與函數外部具有相同名稱的其他變量沒有任何關系,即變量名稱對于函數來說是局部的,這稱為變量的作用域,示例如下:
def func_local(x):print 'x is', xx = 2print 'Chanaged local x to',xx = 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 yprint 'y is', yy = 50print 'Changed local y to', yy = 10 func_global() print 'Value of y is', ydef func_global():global yprint 'y is', yy = 50print 'Changed local y to', yy = 10 func_global() print 'Value of y is', y
執行結果:
y is 10 Changed local y to 50 Value of y is 50y is 10 Changed local y to 50 Value of y is 50
函數參數若是list、set、dict可變參數,在函數內改變參數,會導致該參數發生變化,例如:
def func_local(x):print 'x is', xx.append(10)print 'Chanaged local x to',xx = range(6) func_local(x) print 'x is', xdef func_local(x):print 'x is', xx.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', xx.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', xx.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', xx['x'] = 2print 'Chanaged local x to',xx = dict([('x',1), ('y', 2)]) func_local(x) print 'x is', x
def func_local(x):print 'x is', xx['x'] = 2print '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', xx = (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', xx = (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不變
轉載于:https://www.cnblogs.com/Bella2017/p/7994572.html
總結
以上是生活随笔為你收集整理的python-global全局变量的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 脑功能成像研究之我见-组会讲稿
- 下一篇: 优达学城数据分析笔记1--------数