[譯] Python裝飾器Part II:裝飾器參數(shù)

這是Python裝飾器講解的第二部分,上一篇:Python裝飾器Part I:裝飾器簡介

回顧:不帶參數(shù)的裝飾器

Python裝飾器Part I:裝飾器簡介中,我演示了怎么樣使用無參數(shù)的裝飾器协怒,主要是使用類式裝飾器卑笨,因為這樣更容易理解赤兴。
如果我們創(chuàng)建了一個不帶參數(shù)的裝飾器妖滔,被裝飾的方法會傳遞給裝飾器的構(gòu)造器桶良,然后在被裝飾的函數(shù)被調(diào)用的時候铛楣,裝飾器的__call__()方法就會執(zhí)行。

class decoratorWithoutArguments(object):

    def __init__(self, f):
        """
        If there are no decorator arguments, the function
        to be decorated is passed to the constructor.
        """
        print "Inside __init__()"
        self.f = f

    def __call__(self, *args):
        """
        The __call__ method is not called until the
        decorated function is called.
        """
        print "Inside __call__()"
        self.f(*args)
        print "After self.f(*args)"

@decoratorWithoutArguments
def sayHello(a1, a2, a3, a4):
    print 'sayHello arguments:', a1, a2, a3, a4

print "After decoration"

print "Preparing to call sayHello()"
sayHello("say", "hello", "argument", "list")
print "After first sayHello() call"
sayHello("a", "different", "set of", "arguments")
print "After second sayHello() call"

任何傳遞給被裝飾方法的參數(shù)都將傳遞給__call__()簸州,輸出日志是:

Inside __init__()
After decoration
Preparing to call sayHello()
Inside __call__()
sayHello arguments: say hello argument list
After self.f(*args)
After first sayHello() call
Inside __call__()
sayHello arguments: a different set of arguments
After self.f(*args)
After second sayHello() call

需要注意的是,在“裝飾”階段歧譬,只有__init__()會被調(diào)用;同時只有在被裝飾方法被調(diào)用的時候瑰步,__call__()才會被調(diào)用矢洲。

帶參數(shù)的裝飾器

現(xiàn)在我們把上面的那個例子簡單的改動一下,看看在添加裝飾器參數(shù)的情況下會發(fā)生什么情況:

class decoratorWithArguments(object):

    def __init__(self, arg1, arg2, arg3):
        """
        If there are decorator arguments, the function
        to be decorated is not passed to the constructor!
        """
        print "Inside __init__()"
        self.arg1 = arg1
        self.arg2 = arg2
        self.arg3 = arg3

    def __call__(self, f):
        """
        If there are decorator arguments, __call__() is only called
        once, as part of the decoration process! You can only give
        it a single argument, which is the function object.
        """
        print "Inside __call__()"
        def wrapped_f(*args):
            print "Inside wrapped_f()"
            print "Decorator arguments:", self.arg1, self.arg2, self.arg3
            f(*args)
            print "After f(*args)"
        return wrapped_f

@decoratorWithArguments("hello", "world", 42)
def sayHello(a1, a2, a3, a4):
    print 'sayHello arguments:', a1, a2, a3, a4

print "After decoration"

print "Preparing to call sayHello()"
sayHello("say", "hello", "argument", "list")
print "after first sayHello() call"
sayHello("a", "different", "set of", "arguments")
print "after second sayHello() call"

從輸出結(jié)果來看缩焦,運行的效果發(fā)生了明顯的變化:

Inside __init__()
Inside __call__()
After decoration
Preparing to call sayHello()
Inside wrapped_f()
Decorator arguments: hello world 42
sayHello arguments: say hello argument list
After f(*args)
after first sayHello() call
Inside wrapped_f()
Decorator arguments: hello world 42
sayHello arguments: a different set of arguments
After f(*args)
after second sayHello() call

現(xiàn)在,在“裝飾”階段袁滥,構(gòu)造器和__call__()都會被依次調(diào)用,__call__()也只接受一個函數(shù)對象類型的參數(shù)揩徊,而且必須返回一個裝飾方法去替換原有的方法塑荒,__call__()只會在“裝飾”階段被調(diào)用一次,接著返回的裝飾方法會被實際用在調(diào)用過程中齿税。
盡管這個行為很合理凌箕,構(gòu)造器現(xiàn)在被用來捕捉裝飾器的參數(shù),而且__call__()不能再被當做裝飾方法陌知,相反要利用它來完成裝飾的過程他托。盡管如此,第一次見到這種與不帶參數(shù)的裝飾器迥然不同的行為還是會讓人大吃一驚仆葡,而且它們的編程范式也有很大的不同赏参。

帶參數(shù)的函數(shù)式裝飾器

最后,讓我們看一下更復(fù)雜的函數(shù)式裝飾器沿盅,在這里你不得不一次完成所有的事情:

def decoratorFunctionWithArguments(arg1, arg2, arg3):
    def wrap(f):
        print "Inside wrap()"
        def wrapped_f(*args):
            print "Inside wrapped_f()"
            print "Decorator arguments:", arg1, arg2, arg3
            f(*args)
            print "After f(*args)"
        return wrapped_f
    return wrap

@decoratorFunctionWithArguments("hello", "world", 42)
def sayHello(a1, a2, a3, a4):
    print 'sayHello arguments:', a1, a2, a3, a4

print "After decoration"

print "Preparing to call sayHello()"
sayHello("say", "hello", "argument", "list")
print "after first sayHello() call"
sayHello("a", "different", "set of", "arguments")
print "after second sayHello() call"

輸出結(jié)果:

Inside wrap()
After decoration
Preparing to call sayHello()
Inside wrapped_f()
Decorator arguments: hello world 42
sayHello arguments: say hello argument list
After f(*args)
after first sayHello() call
Inside wrapped_f()
Decorator arguments: hello world 42
sayHello arguments: a different set of arguments
After f(*args)
after second sayHello() call

函數(shù)式裝飾器的返回值必須是一個函數(shù)把篓,能包裝原有被包裝函數(shù)。也就是說腰涧,Python會在裝飾發(fā)生的時候拿到并且調(diào)用這個返回的函數(shù)結(jié)果韧掩,然后傳遞給被裝飾的函數(shù),這就是為什么我們在裝飾器的實現(xiàn)里嵌套定義了三層的函數(shù)窖铡,最里層的那個函數(shù)是新的替換函數(shù)疗锐。
因為閉包的特性, wrapped_f()在不需要像在類式裝飾器例子中一樣顯示存儲arg1, arg2, arg3這些值的情況下费彼,就能夠訪問這些參數(shù)滑臊。不過,這恰巧是我覺得“顯式比隱式更好”的例子箍铲。盡管函數(shù)式裝飾器可能更加精簡一點雇卷,但類式裝飾器會更加容易理解并因此更容易被修改和維護。

原文地址:Python Decorators II: Decorator Arguments

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末颠猴,一起剝皮案震驚了整個濱河市关划,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌翘瓮,老刑警劉巖贮折,帶你破解...
    沈念sama閱讀 221,635評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異春畔,居然都是意外死亡脱货,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,543評論 3 399
  • 文/潘曉璐 我一進店門律姨,熙熙樓的掌柜王于貴愁眉苦臉地迎上來振峻,“玉大人,你說我怎么就攤上這事择份】勖希” “怎么了?”我有些...
    開封第一講書人閱讀 168,083評論 0 360
  • 文/不壞的土叔 我叫張陵荣赶,是天一觀的道長凤价。 經(jīng)常有香客問我,道長拔创,這世上最難降的妖魔是什么利诺? 我笑而不...
    開封第一講書人閱讀 59,640評論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮剩燥,結(jié)果婚禮上慢逾,老公的妹妹穿的比我還像新娘。我一直安慰自己灭红,他們只是感情好侣滩,可當我...
    茶點故事閱讀 68,640評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著变擒,像睡著了一般君珠。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上娇斑,一...
    開封第一講書人閱讀 52,262評論 1 308
  • 那天策添,我揣著相機與錄音,去河邊找鬼毫缆。 笑死舰攒,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的悔醋。 我是一名探鬼主播摩窃,決...
    沈念sama閱讀 40,833評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼芬骄!你這毒婦竟也來了猾愿?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,736評論 0 276
  • 序言:老撾萬榮一對情侶失蹤账阻,失蹤者是張志新(化名)和其女友劉穎蒂秘,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體淘太,經(jīng)...
    沈念sama閱讀 46,280評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡姻僧,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,369評論 3 340
  • 正文 我和宋清朗相戀三年规丽,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片撇贺。...
    茶點故事閱讀 40,503評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡赌莺,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出松嘶,到底是詐尸還是另有隱情艘狭,我是刑警寧澤,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布翠订,位于F島的核電站巢音,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏尽超。R本人自食惡果不足惜官撼,卻給世界環(huán)境...
    茶點故事閱讀 41,870評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望似谁。 院中可真熱鬧歧寺,春花似錦、人聲如沸棘脐。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,340評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽蛀缝。三九已至顷链,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間屈梁,已是汗流浹背嗤练。 一陣腳步聲響...
    開封第一講書人閱讀 33,460評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留在讶,地道東北人煞抬。 一個月前我還...
    沈念sama閱讀 48,909評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像构哺,于是被迫代替她去往敵國和親革答。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,512評論 2 359

推薦閱讀更多精彩內(nèi)容