因為最近想總結一下閉包和裝飾器,有點細節(jié)總是理不順,于是找了一下B站上播放量大的,其中一個下面評論很多都說講的很好,但是我聽了一下,關于閉包的地方講解的就有明顯錯誤。與fluent python和effective python上有矛盾,其實python cookbook上也沒說一定是函數(shù)作為參數(shù),只是說可以。但是B站有些視頻講解時,竟然說閉包一定是傳入的參數(shù)是函數(shù),其實這個就差遠了。所以大家看一些東西時,最好還是看經(jīng)典教材,畢竟網(wǎng)上一些講解的視頻,沒有經(jīng)過審核,再者講解者自身水平參差不齊。
我們提供的服務有:網(wǎng)站建設、網(wǎng)站設計、微信公眾號開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認證、蔡甸ssl等。為上千企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務,是有科學管理、有技術的蔡甸網(wǎng)站制作公司
總結后,發(fā)現(xiàn)裝飾器真是個好東西,靈活方便。裝飾器是通過閉包來實現(xiàn)的,可以這么說兩者之間的關系。
fluent python 2nd中關于閉包的說法。
A closure is a function-let’s call it f – with an extend scope that encompasses variables referenced in the body of f that are not global variables nor local variables of f. Such variables must come from the local scope of an outer function which encompasses f. It does not matter whether the function is anonymous or not; what matters is that it can access nonglobal variables that are defined outside of its body.
閉包是一個函數(shù) f +一個/些變量,這些變量在閉包內(nèi)引用,但是不是global變量也不是f的局部變量。這些變量必須來自包含函數(shù)f的外部函數(shù)的局部區(qū)域。函數(shù)是不是匿名函數(shù)無所謂,關鍵是f可以訪問那些定義在 f 外部的非全局變量。書中給了一個圖例,很清晰,到底什么是閉包。
從這個圖的定義來看,閉包是函數(shù)并且這個函數(shù)可以訪問非global的自由變量。當然一般閉包首先涉及到嵌套函數(shù)(函數(shù)內(nèi)有函數(shù)),也涉及到高階函數(shù)(傳入的參數(shù)是函數(shù)或者返回值是函數(shù))。但是并不像有些人講的那樣,閉包一定是傳入函數(shù)。
如下是閉包的一個典型用法,這里閉包外的函數(shù)沒有參數(shù)的。
def make_averager(): count = 0 total = 0 def averager(new_value): nonlocal count,total count += 1 total += new_value return total/count return averager # 返回的是函數(shù),帶括號返回的函數(shù)運行結果 avg = make_averager() # an object of function make_averager print(avg.__name__) # the name is averager avg(10) avg(11) res = avg(13) res = avg(14) print(res)
分享名稱:閉包和裝飾器的關系
文章源于:http://m.kartarina.com/article38/dsojosp.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供企業(yè)網(wǎng)站制作、網(wǎng)站策劃、商城網(wǎng)站、企業(yè)建站、靜態(tài)網(wǎng)站、微信小程序
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)