鍍金池/ 教程/ Python/ 裝飾器類
<code>open</code>函數(shù)
Python 2系列版本
可迭代對象(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>從句
對象自省
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ù)的裝飾器
對象變動(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)
裝飾器
一切皆對象
使用C擴(kuò)展
使用 <code>*args</code> 和 <code>**kwargs</code> 來調(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)
使用場景
生成器(Generators)
多個(gè)return值
關(guān)于原作者
函數(shù)緩存 (Function caching)
Python進(jìn)階

裝飾器類

現(xiàn)在我們有了能用于正式環(huán)境的logit裝飾器,但當(dāng)我們的應(yīng)用的某些部分還比較脆弱時(shí),異常也許是需要更緊急關(guān)注的事情。比方說有時(shí)你只想打日志到一個(gè)文件。而有時(shí)你想把引起你注意的問題發(fā)送到一個(gè)email,同時(shí)也保留日志,留個(gè)記錄。這是一個(gè)使用繼承的場景,但目前為止我們只看到過用來構(gòu)建裝飾器的函數(shù)。

幸運(yùn)的是,類也可以用來構(gòu)建裝飾器。那我們現(xiàn)在以一個(gè)類而不是一個(gè)函數(shù)的方式,來重新構(gòu)建logit

from functools import wraps

class logit(object):
    def __init__(self, logfile='out.log'):
        self.logfile = logfile

    def __call__(self, func):
        @wraps(func)
        def wrapped_function(*args, **kwargs):
            log_string = func.__name__ + " was called"
            print(log_string)
            # 打開logfile并寫入
            with open(self.logfile, 'a') as opened_file:
                # 現(xiàn)在將日志打到指定的文件
                opened_file.write(log_string + '\n')
            # 現(xiàn)在,發(fā)送一個(gè)通知
            self.notify()
            return func(*args, **kwargs)
        return wrapped_function

    def notify(self):
        # logit只打日志,不做別的
        pass

這個(gè)實(shí)現(xiàn)有一個(gè)附加優(yōu)勢,在于比嵌套函數(shù)的方式更加整潔,而且包裹一個(gè)函數(shù)還是使用跟以前一樣的語法:

@logit()
def myfunc1():
    pass

現(xiàn)在,我們給logit創(chuàng)建子類,來添加email的功能(雖然email這個(gè)話題不會(huì)在這里展開)。

class email_logit(logit):
    '''
    一個(gè)logit的實(shí)現(xiàn)版本,可以在函數(shù)調(diào)用時(shí)發(fā)送email給管理員
    '''
    def __init__(self, email='admin@myproject.com', *args, **kwargs):
        self.email = email
        super(email_logit, self).__init__(*args, **kwargs)

    def notify(self):
        # 發(fā)送一封email到self.email
        # 這里就不做實(shí)現(xiàn)了
        pass

從現(xiàn)在起,@email_logit將會(huì)和@logit產(chǎn)生同樣的效果,但是在打日志的基礎(chǔ)上,還會(huì)多發(fā)送一封郵件給管理員。