Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Python 裝飾器:語法、六種用法與實戰場景

前言

前幾天在看 Flask 框架時卡住了,回頭補裝飾器的功課。讀了不少文章後,我把適合自己思路的部分整理出來分享給大家。

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

一、裝飾器是什麼

裝飾器是 Python 的高級語法,主要功能是對一個函數、方法或類進行加工,為已存在的物件加上額外功能,同時提升程式碼可讀性。它屬於設計模式的一種,常用於有「切面」需求的場景,最經典的就是插入日誌、效能測試、事務處理。

二、語法

@dec2
@dec1
def func(arg1, arg2, ...):
    ...
    return funx

上面等價於:

def func(arg1, arg2, ...):
    pass
func = dec2(dec1(func))

裝飾器接收一個可呼叫物件作為輸入,並回傳一個新的可呼叫物件。在新增的函數中我們可以加入需要的功能,並透過呼叫原有函數來保留原本的功能。

三、六種用法

3.1 不帶參數的裝飾器(錯誤示範)

def deco(func):
    """無參數 decorator 聲明時必須有一個參數,接收被裝飾的方法"""
    print "before myfunc() called."
    func()
    print "after myfunc() called."
    return func

@deco
def myfunc():
    print " myfunc() called."

myfunc()
myfunc()

輸出:

before myfunc() called.
 myfunc() called.
 after myfunc() called.
 myfunc() called.   <-- 函數多執行一次的輸出
 myfunc() called.   <-- 第二次呼叫,裝飾器不生效

問題很明顯:只在第一次被呼叫,而且原函數多跑了一次。正確寫法是回傳內嵌函數而不是原函數:

def deco(func):
    def _deco():
        print "before myfunc() called."
        func()
        print "after myfunc() called."
    return _deco      # 不需要 return func

@deco
def myfunc():
    print " myfunc() called."
    return 'OK'

myfunc()
myfunc()

這樣每次呼叫都會經過裝飾器。

3.2 裝飾帶參數的函數

def deco(func):
    def _deco(a, b):
        print("before myfunc() called.")
        ret = func(a, b)
        print(" after myfunc() called. result: %s" % ret)
        return ret
    return _deco

@deco
def myfunc(a, b):
    print(" myfunc(%s,%s) called." % (a, b))
    return a + b

myfunc(1, 2)
myfunc(3, 4)

輸出:

before myfunc() called.
 myfunc(1,2) called.
 after myfunc() called. result: 3
before myfunc() called.
 myfunc(3,4) called.
 after myfunc() called. result: 7

重點是:內嵌函數的形參與回傳值要和原函數一致,裝飾函數回傳的是內嵌的包裝函數。

3.3 裝飾器本身帶參數

def decoWithArgs(arg):
    """帶參數的 decorator 在呼叫時只接收自己的參數,不接收被裝飾的函數,
       所以必須回傳一個 decorator 函數,由它來封裝被裝飾的函數"""
    def newDeco(func):
        def replaceFunc():
            print "Enter decorator %s" % arg   # 額外操作
            return func()
        return replaceFunc
    return newDeco

@decoWithArgs("demo")
def MyFunc():
    print "Enter MyFunc"

MyFunc()

輸出:

Enter decorator demo
Enter MyFunc

這個形式適用於「原函數沒有參數、需要額外印出資訊」的情況,最常見的用途就是加上日誌。

3.4 裝飾參數數量不確定的函數

下面是一個郵件異步發送的例子,用 *args/**kwargs 承接任意參數:

from threading import Thread

def async(f):
    def wrapper(*args, **kwargs):
        thr = Thread(target=f, args=args, kwargs=kwargs)
        thr.start()
    return wrapper

@async
def send_async_email(msg):
    mail.send(msg)

def send_email(subject, sender, recipients, text_body, html_body):
    msg = Message(subject, sender=sender, recipients=recipients)
    msg.body = text_body
    msg.html = html_body
    send_async_email(msg)

這個裝飾器可以套用到一切需要異步處理的功能上,程式碼復用度非常高。

3.5 讓裝飾器帶類參數

class locker:
    def __init__(self):
        print("locker.__init__() should be not called.")

    @staticmethod
    def acquire():
        print("locker.acquire() called.(這是靜態方法)")

    @staticmethod
    def release():
        print(" locker.release() called.(不需要物件實例)")

def deco(cls):
    """cls 必須實作 acquire 和 release 靜態方法"""
    def _deco(func):
        def __deco():
            print("before %s called [%s]." % (func.__name__, cls))
            cls.acquire()
            try:
                return func()
            finally:
                cls.release()
        return __deco
    return _deco

@deco(locker)
def myfunc():
    print(" myfunc() called.")

myfunc()
myfunc()

輸出:

before myfunc called [__main__.locker].
locker.acquire() called.(這是靜態方法)
 myfunc() called.
 locker.release() called.(不需要物件實例)

用 try/finally 保證 release 一定會執行,這正是「有切面需求」時最實用的寫法。

總結

當我們對某個方法套用裝飾器後,實際上就改變了「被裝飾函數名稱所引用的程式碼塊入口點」,讓它重新指向裝飾器回傳的那個函數入口。因此我們可以用 decorator 改變原有函數的功能、加上各種操作,甚至完全替換原有實作。

無需操作系統直接運行 Python 代碼 https://www.linuxidc.com/Linux/2015-05/117357.htm

CentOS 上源碼安裝 Python3.4 https://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun).[高清PDF中文版] https://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.(周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] https://www.linuxidc.com/Linux/2013-11/92693.htm

Python 腳本獲取 Linux 系統信息 https://www.linuxidc.com/Linux/2013-08/88531.htm

在 Ubuntu 下用 Python 搭建桌面算法交易研究環境 https://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 https://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved