python 閉包 裝飾器

來源:互聯網
上載者:User

標籤:

閉包:是由函數和其他相關的引用環境組合而成的實體。

如果一個函數內部,對在外部範圍的變數進行引用,那麼內建函式就被認為是閉包(closure)。

A CLOSURE is a function object that remembers values in enclosing scopes regardless of whether those scopes are still present in memory.

 

>>> def hellocounter(name):

count=[0]

def counter():

count[0]+=1

print "Hello,",name,‘,‘,str(count[0])," access"

return counter

 

>>> hello = hellocounter("zxahu")

>>> hello()

Hello, zxahu , 1  access

>>> hello()

Hello, zxahu , 2  access

這裡,counter()中調用了外部的變數,所以它這裡是閉包

 

__closure__ 屬性返回一組cell object,它包含了在閉包環境中的變數,注意,如果變數是引用,那麼cell中儲存的就是引用,如果是不可變得變數,那麼存的是變數

>>> hello.__closure__

(<cell at 0x02DF2FD0: list object at 0x02DF4DA0>, <cell at 0x02E057B0: str object at 0x02E057C0>)

>>> hello.__closure__[0].cell_contents

[2]

>>> hello.__closure__[1].cell_contents

‘zxahu‘

 

 

裝飾器“@”decorator

若要增強某函數的功能,但又不希望修改該函數的定義,這種代碼運行期間動態增加功能的方式,稱為裝飾器

def deco(func):
def __decorator():
print "decorator running... prepare function"
func()
print "function done"
return __decorator

@deco
def test():
print "test func running..."

test()

輸出:

decorator running... prepare function
test func running...
function done

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.