前言
裝飾器是個令人頭疼的概念杖小,下面我用最最簡單的例子和最最詳細的表達來解釋一下這個概念,希望能對大家有所幫助烛愧。
裝飾器
裝飾器:用于在不改變原函數(shù)的情況下酪惭,給原函數(shù)擴張功能
解釋:
我們先編寫一個簡單的打印字符串的函數(shù)希痴,如下:
def print_ysf():
print 'ysf'
調(diào)用函數(shù)print_ysf:
>>> print_ysf()
ysf
這個函數(shù)只有一個功能就是打印出ysf,但我現(xiàn)在要想在打印ysf之前先打印出hello,單不改變print_ysf函數(shù)春感,那怎么辦呢砌创,這個時候就要用到裝飾器,
我先把具體用法寫下來鲫懒,再來解釋.
def decorator(func):
def print_hello():
print 'hello'
return func()
return print_hello
@decorator
def print_ysf():
print 'ysf'
調(diào)用函數(shù)print_ysf
>>>print_ysf()
hello
ysf
神奇吧纺铭,這就是裝飾器的功能,在沒有改變print_ysf函數(shù)的情況下刀疙,增加了print_ysf函數(shù)的功能舶赔,下面我來解釋一些其運行原理:
那我們現(xiàn)在看這個函數(shù):
def decorator(func):
def print_hello():
print 'hello'
return func()
return print_hello
@decorator
def print_ysf():
print 'ysf'
首先記住一點:函數(shù)只有在調(diào)用時才被執(zhí)行,因此乍一看改函數(shù)什么都沒有被執(zhí)行谦秧,但是因為有@decorator就不一樣了
當python解釋器掃到@decorator時會執(zhí)執(zhí)行如下步驟:
1.將@decorator下面的函數(shù)竟纳,即print_ysf函數(shù)作為decorator函數(shù)的參數(shù)撵溃,也就是decorator(print_ysf)
2.執(zhí)行decorator(print_ysf)函數(shù)
3.現(xiàn)在執(zhí)行decorator(print_ysf)函數(shù),我們發(fā)現(xiàn)decorator(print_ysf)還有一個print_hello()函數(shù)锥累,但因為沒有被調(diào)用缘挑,因此不執(zhí)行,
繼續(xù)往下桶略,那么其實就是執(zhí)行了 return print_hello
4.將返回的print_hello函數(shù)賦給給@decorator下面的函數(shù)print_ysf语淘,即print_ysf = print_hello
5.然后我們再命令行輸入print_ysf(),其實相當于執(zhí)行了print_hello()际歼,那么就會按照print_hello函數(shù)的內(nèi)部代碼惶翻,
先print 'hello',然后return func(),而func就是decorato函數(shù)通過@decorator傳進來的參數(shù)鹅心,即原本的print_ysf函數(shù)吕粗,于是就又執(zhí)行了原本的
print_hello函數(shù),因此會執(zhí)行print ‘ysf’
6.所以最終輸出為:
hello
ysf
后記
解釋完畢旭愧,貧僧作為一個python初學者颅筋,已經(jīng)盡力了,希望能對大家有所幫助吧输枯。