8.局部变量/全局变量global/内嵌函数/闭包nonlocal
生活随笔
收集整理的這篇文章主要介紹了
8.局部变量/全局变量global/内嵌函数/闭包nonlocal
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
函數:有返回值
過程:無返回值
注解:在python中,只有函數(每個函數都有返回值),沒有過程>>> def hello():print("first")>>> temp = hello() #解釋:雖然沒有寫明返回值,但是
first
>>> print(temp) #打印出來的temp卻有值None
None
>>>
python可以返回多個值
>>> def back1(): #返回的值存放在stuple中return 1,2,'Curry'>>> back1() (1, 2, 'Curry') #元祖stuple>>> def back2(): #返回的值存放在list中return [1,2,'Curry']>>> back2() [1, 2, 'Curry'] #列表list變量的作用域(局部變量,全局變量)
存放位置:棧、全局變量區在函數里邊定義的參數、變量,它們就是局部變量,出了這個函數,該變量就失效。 函數外部無法訪問到這些局部變量。在函數外部定義的變量,全局變量。局部變量、全局變量如果同名,在函數內部,局部變量會覆蓋全局變量的值。 >>> count = 5 #全局變量 >>> def MyFun():count = 10 #局部變量print(count)>>> MyFun() 10 >>> print(count) 5global關鍵字
告訴python編譯器,把后面的變量變成全局變量: >>> count = 5 #全局變量 >>> def MyFun():global count #把count變量變成全局變量count = 10 #局部變量print(count)>>> MyFun() 10 >>> print(count) 10內嵌函數(內部函數):函數中有函數
1. >>> def f2(): #先定義f2()函數print("f2()")>>> def f1(): #在f1()函數中調用f2()函數f2()>>> f1() f2()2.直接在f1()中定義并調用f2()函數 >>> def f1():def f2(): #在f1()函數中聲明f2()函數print("f2 in f1")f2() #在f1()函數中實現f2()函數>>> f1() f2 in f1 【注解】函數f2()是函數f1()的內嵌/內部函數,f2的作用域只在f1的內部生效,超出f1外,函數f2不可見。閉 包
http://www.cnblogs.com/ma6174/archive/2013/04/15/3022548.html
【閉包的作用域問題】
>>> def f():a = 1 #② a是g()函數的“非全局的外部變量”def g():a = 2print aprint a #①return g>>> f()() 1 2先執行① 在return g中執行② >>> def f():count = 5 #5是g()函數"非全局的的外部變量",因此在g()函數中不認識count=5def g():count = count+100 #因此count在此時并沒有初始值,所以沒有初始值的count+100會報錯return g 執行結果:報錯 >>> f()()Traceback (most recent call last):File "<pyshell#157>", line 1, in <module>f()()File "<pyshell#156>", line 4, in gcount = count+100 UnboundLocalError: local variable 'count' referenced before assignment #count在引用前沒有被賦值【解決方案1】使用list列表:把"非全局變量的外部變量"放在list中, 然后再使用。【因為】在python中,list中的元素是全局變量,不是局部變量。 >>> def f():count = [5,10,121,20]def g():count[0] = count[0]+100count[1] = count[1]+100print count[0],count[1]return g>>> f()() 105 110上面把[5,10,121,20]放在list中,相當于變成了全局變量, 不會出現沒有賦值的錯誤。【解決方案2】python3中引出了關鍵字nonlocal def hellocounter (name):count=0 def counter():nonlocal count #聲明為全局變量count+=1print 'Hello,',name,',',str(count[0])+' access!'return counterhello = hellocounter('ma6174') hello() hello() hello() Python中怎么創建閉包? 在Python中創建一個閉包可以歸結為以下三點: - 閉包函數必須有內嵌函數 - 內嵌函數需要引用該嵌套函數上一級namespace中的變量 - 閉包函數必須返回內嵌函數http://www.jb51.net/article/54498.htm
總結
以上是生活随笔為你收集整理的8.局部变量/全局变量global/内嵌函数/闭包nonlocal的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 7.函数def
- 下一篇: 9.匿名函数:lambda表达式/fil