裝飾器是一種設(shè)計(jì)模式,它提供了強(qiáng)大的復(fù)用非業(yè)務(wù)邏輯的能力,經(jīng)典的應(yīng)用場景有日志記錄、性能測試、事務(wù)處理等。
下面分幾個(gè)部分逐步介紹python中的裝飾器。
1、python如何理解函數(shù)
在介紹裝飾器之前,先介紹一下函數(shù)。理解python中的函數(shù),首先要建立這樣認(rèn)知:在python中,一切皆對象。變量、列表、字典,甚至函數(shù)、類、元類等都是對象。
這里講的函數(shù)作為第一類對象,可以將它:
- 賦值給一個(gè)變量或存入其他數(shù)據(jù)結(jié)構(gòu),如列表、字典等
- 作為參數(shù)竄地給其他函數(shù)
- 作為函數(shù)的返回值
>>> def foo():
... i = 1
... print i
...
>>> a = foo
>>> a
<function foo at 0x100700320>
>>> b = [str, foo]
>>> b
[<type 'str'>, <function foo at 0x100700320>]
>>> def bar(func):
... return func
...
>>> c = bar(foo)
>>> c
<function foo at 0x100700320>
>>> c()
1
>>>
另外,實(shí)現(xiàn)了__call__方法類的實(shí)例也可以像函數(shù)一樣使用。
>>> class Bar:
... def __init__(self, i):
... self.i = i
... def __call__(self, j):
... return self.i + j
...
>>> foo = Bar(1)
>>> foo(2)
3
建立了以上的認(rèn)知之后,我們來介紹裝飾器。
2、裝飾器其實(shí)是一種閉包
前面介紹過,閉包是一種引用了自由變量的函數(shù)。
>>> def print_msg(msg):
... def printer():
... print('start....')
... print(msg)
... print('end....')
... return printer
...
>>> another_print = print_msg('hello')
>>> another_print()
start....
hello
end....
>>>
那裝飾器呢?
>>> def print_msg(func):
... def printer():
... print('starting...')
... func()
... print('end....')
... return printer
...
>>> def foo():
... print('hello')
...
>>> another_print = print_msg(foo)
>>> another_print()
starting...
hello
end....
基本沒有修改什么邏輯,只是把參數(shù)替換成了函數(shù),就變成了一個(gè)簡單的裝飾器。所以,裝飾器其實(shí)是一種以函數(shù)作為參數(shù)的閉包。這個(gè)print_msg就是裝飾器,它封裝一些可復(fù)用的非業(yè)務(wù)邏輯,而被裝飾的foo可以專注于業(yè)務(wù)邏輯。這樣整個(gè)設(shè)計(jì)就非常清晰,而且增加了可讀性。
3、裝飾器的兩種類型
裝飾器有兩種類型:函數(shù)和類。
函數(shù)裝飾器,就像上面例子中一樣,是一個(gè)函數(shù)。但是裝飾器不僅可以是函數(shù),還可以是類。類裝飾器在靈活性、內(nèi)聚性、封裝型等方面優(yōu)點(diǎn)更未突出。
前面看過了函數(shù)裝飾器的例子,下面看一個(gè)類裝飾器的例子
>>> class Dec:
... def __init__(self, func):
... self._func = func
... def __call__(self):
... print('start....')
... self._func()
... print('end....')
...
>>> def para():
... print('hello')
...
>>> a = Dec(para)
>>> a
<__main__.Dec instance at 0x10071c680>
>>> a()
start....
hello
end....
4、參數(shù)設(shè)置
4.1裝飾器參數(shù)
裝飾器的使用非常靈活,需要時(shí)可以設(shè)置必要的參數(shù)。
def outer(a):
def print_msg(func):
def printer():
if a == 1:
print('start...')
func()
else:
func()
return printer
return print_msg
def foo():
print('hello')
another_print = outer(1)
another_print(foo)()
start...
hello
4.2被裝飾函數(shù)參數(shù)
如果被裝飾函數(shù)需要傳入?yún)?shù),可以在執(zhí)行該函數(shù)的嵌套函數(shù)中設(shè)置。上面例子中,可以在printer中設(shè)置需要的相關(guān)參數(shù)。
def printer(*args, **kwargs):
if a == 1:
print('start....')
func(*args, **kwargs)
else:
func(*args, **kwargs)
5、@語法糖
@符號(hào)是裝飾器的語法糖,將@符號(hào)和裝飾器名稱放在被裝飾函數(shù)定義的地方,這樣在使用函數(shù)時(shí)不用顯示的調(diào)用裝飾器, 而且這樣并不會(huì)影響參數(shù)設(shè)置。
def outer(a):
def print_msg(func):
def printer():
if a == 1:
print(func.__name__)
func()
else:
func()
return printer
return print_msg
@outer(a=1)
def foo():
print('hello')
foo()
start...
hello
參考目錄: