鍍金池/ 教程/ Python/ 你的第一個(gè)裝飾器
<code>open</code>函數(shù)
Python 2系列版本
可迭代對(duì)象(Iterable)
異常
在函數(shù)中嵌入裝飾器
你的第一個(gè)裝飾器
上下文管理器(Context managers)
<code>set</code>(集合)數(shù)據(jù)結(jié)構(gòu)
裝飾器類
字典推導(dǎo)式(<code>dict</code> comprehensions)
<code>Reduce</code>
捐贈(zèng)名單
<code>Filter</code>
<code>try/else</code>從句
*args 的用法
<code>dir</code>
處理異常
<code>else</code>從句
對(duì)象自省
For - Else
18. 一行式
Python 3.2及以后版本
Global和Return
基于類的實(shí)現(xiàn)
容器(<code>Collections</code>)
23. 協(xié)程
推薦閱讀
譯者后記
<code>*args</code> 和 <code>**kwargs</code>
**kwargs 的用法
生成器(Generators)
迭代(Iteration)
基于生成器的實(shí)現(xiàn)
將函數(shù)作為參數(shù)傳給另一個(gè)函數(shù)
日志(Logging)
三元運(yùn)算符
<code>inspect</code>模塊
枚舉
Map,F(xiàn)ilter 和 Reduce
各種推導(dǎo)式(comprehensions)
從函數(shù)中返回函數(shù)
列表推導(dǎo)式(<code>list</code> comprehensions)
處理多個(gè)異常
帶參數(shù)的裝飾器
對(duì)象變動(dòng)(Mutation)
22. 目標(biāo)Python2+3
迭代器(Iterator)
虛擬環(huán)境(virtualenv)
<code>__slots__</code>魔法
什么時(shí)候使用它們?
Python/C API
<code>Map</code>
SWIG
授權(quán)(Authorization)
裝飾器
一切皆對(duì)象
使用C擴(kuò)展
使用 <code>*args</code> 和 <code>**kwargs</code> 來(lái)調(diào)用函數(shù)
17. <code>lambda</code>表達(dá)式
集合推導(dǎo)式(<code>set</code> comprehensions)
<code>type</code>和<code>id</code>
在函數(shù)中定義函數(shù)
<code>finally</code>從句
CTypes
調(diào)試(Debugging)
使用場(chǎng)景
生成器(Generators)
多個(gè)return值
關(guān)于原作者
函數(shù)緩存 (Function caching)
Python進(jìn)階

你的第一個(gè)裝飾器

在上一個(gè)例子里,其實(shí)我們已經(jīng)創(chuàng)建了一個(gè)裝飾器!現(xiàn)在我們修改下上一個(gè)裝飾器,并編寫(xiě)一個(gè)稍微更有用點(diǎn)的程序:

def a_new_decorator(a_func):

    def wrapTheFunction():
        print("I am doing some boring work before executing a_func()")

        a_func()

        print("I am doing some boring work after executing a_func()")

    return wrapTheFunction

def a_function_requiring_decoration():
    print("I am the function which needs some decoration to remove my foul smell")

a_function_requiring_decoration()
#outputs: "I am the function which needs some decoration to remove my foul smell"

a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
#now a_function_requiring_decoration is wrapped by wrapTheFunction()

a_function_requiring_decoration()
#outputs:I am doing some boring work before executing a_func()
#        I am the function which needs some decoration to remove my foul smell
#        I am doing some boring work after executing a_func()

你看明白了嗎?我們剛剛應(yīng)用了之前學(xué)習(xí)到的原理。這正是python中裝飾器做的事情!它們封裝一個(gè)函數(shù),并且用這樣或者那樣的方式來(lái)修改它的行為?,F(xiàn)在你也許疑惑,我們?cè)诖a里并沒(méi)有使用@符號(hào)?那只是一個(gè)簡(jiǎn)短的方式來(lái)生成一個(gè)被裝飾的函數(shù)。這里是我們?nèi)绾问褂聾來(lái)運(yùn)行之前的代碼:

@a_new_decorator
def a_function_requiring_decoration():
    """Hey you! Decorate me!"""
    print("I am the function which needs some decoration to "
          "remove my foul smell")

a_function_requiring_decoration()
#outputs: I am doing some boring work before executing a_func()
#         I am the function which needs some decoration to remove my foul smell
#         I am doing some boring work after executing a_func()

#the @a_new_decorator is just a short way of saying:
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)

希望你現(xiàn)在對(duì)Python裝飾器的工作原理有一個(gè)基本的理解。如果我們運(yùn)行如下代碼會(huì)存在一個(gè)問(wèn)題:

print(a_function_requiring_decoration.__name__)
# Output: wrapTheFunction

這并不是我們想要的!Ouput輸出應(yīng)該是“a_function_requiring_decoration”。這里的函數(shù)被warpTheFunction替代了。它重寫(xiě)了我們函數(shù)的名字和注釋文檔(docstring)。幸運(yùn)的是Python提供給我們一個(gè)簡(jiǎn)單的函數(shù)來(lái)解決這個(gè)問(wèn)題,那就是functools.wraps。我們修改上一個(gè)例子來(lái)使用functools.wraps:

from functools import wraps

def a_new_decorator(a_func):
    @wraps(a_func)
    def wrapTheFunction():
        print("I am doing some boring work before executing a_func()")
        a_func()
        print("I am doing some boring work after executing a_func()")
    return wrapTheFunction

@a_new_decorator
def a_function_requiring_decoration():
    """Hey yo! Decorate me!"""
    print("I am the function which needs some decoration to "
          "remove my foul smell")

print(a_function_requiring_decoration.__name__)
# Output: a_function_requiring_decoration

現(xiàn)在好多了。我們接下來(lái)學(xué)習(xí)裝飾器的一些常用場(chǎng)景。

藍(lán)本規(guī)范:

from functools import wraps
def decorator_name(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if not can_run:
            return "Function will not run"
        return f(*args, **kwargs)
    return decorated

@decorator_name
def func():
    return("Function is running")

can_run = True
print(func())
# Output: Function is running

can_run = False
print(func())
# Output: Function will not run

注意:@wraps接受一個(gè)函數(shù)來(lái)進(jìn)行裝飾,并加入了復(fù)制函數(shù)名稱、注釋文檔、參數(shù)列表等等的功能。這可以讓我們?cè)谘b飾器里面訪問(wèn)在裝飾之前的函數(shù)的屬性。

上一篇:推薦閱讀下一篇:裝飾器