python全域變數-局部變數用法和區別

來源:互聯網
上載者:User

標籤: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全域變數-局部變數用法和區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.