標籤:python全域變數 python局部變數 全域和局部變數區別
對於很多初學的同學,對全域和局部變數容易混淆,看看下面給大家的講解相信都應該明白
兩者的區別了。
定義:
全域變數:在模組內、在所有函數的外面、在class外面
局部變數:在函數內、在class的方法內
下面來看看例子
a="hello" #全域變數a
def test():
global a#調用全域變數a
b =a #test方法裡之後再調用a時,都是全域的a
print(b,a)
test()
在test函數裡調用全域變數a,看看運行後的結果
650) this.width=650;" src="https://s1.51cto.com/oss/201711/13/3f8376ea0b65d3b5f5a220194a9ca838.jpg-wh_500x0-wm_3-wmp_4-s_4037831910.jpg" title="2.jpg" alt="3f8376ea0b65d3b5f5a220194a9ca838.jpg-wh_" />
運行後都是全域變數的值hello
a="hello" #全域變數a
def test():
a="hell0 local" #定義了一個局部變數a
b =a #test方法裡之後再調用a時,都是局部的a
print(b+",",a)
test()
這裡在函數test裡面再定義了一個a,這個a就為局部變數了,之後在test裡調用的a全都是局部的a。看看運行結果:
650) this.width=650;" src="https://s1.51cto.com/oss/201711/13/9ad522d1daff3fc9b72f1303ea8642ea.jpg-wh_500x0-wm_3-wmp_4-s_3765295846.jpg" title="4.jpg" alt="9ad522d1daff3fc9b72f1303ea8642ea.jpg-wh_" />
a="hello" #全域變數a
def test():
global a
a="hell0 global" #修改全域變數a的值
b =a #test方法之裡後再調用a時,都是全域的a
print(b+",",a)
test()
在函數test裡面先聲明用的是全域的a,然後對a進行修改,就等於是修改了全域變數a的值。
看看運行結果:
650) this.width=650;" src="https://s1.51cto.com/oss/201711/13/10ba1d3d18cf66a41b0e674ec34f630d.jpg-wh_500x0-wm_3-wmp_4-s_2077495136.jpg" title="5.jpg" alt="10ba1d3d18cf66a41b0e674ec34f630d.jpg-wh_" />
註:在方法內部的變數是在=號前面的,那肯定是局部變數。如果是第一次出現在=號後
面的,那肯定是調用的全域變數;全域變數可以在函數裡面調用,局部變數只能在對應的函
數裡面調用,在該函數外面任何地方都無法被調用。
有問題加QQ群交流610845268
本文出自 “IT蟲” 部落格,請務必保留此出處http://laomomo.blog.51cto.com/6595318/1981193
python全域變數-局部變數用法和區別