python中global的用法——再讀python簡明教程


今天看了知乎@蕭井陌的編程入門指南,想重溫一下 《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
View Code

執行結果:

y is 10
Changed local y to 50
Value of y is 50
View Code

函數參數若是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
View Code

執行結果

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]
View Code
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
View Code

執行結果:

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])
View Code
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
View Code

執行結果:

x is {'y': 2, 'x': 1}
Chanaged local x to {'y': 2, 'x': 2}
x is {'y': 2, 'x': 2}
View Code
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
View Code

執行結果

x is (1, 2, 3)
Chanaged local x to (4, 5, 6)
x is (1, 2, 3)
View Code

若傳入可變參數如list、set、dict,在函數內部對參數做出修改,參數本身發生變化,tuple、str不變


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM