裝飾器是一種設計模式,它提供了強大的複用非業務邏輯的能力,經典的應用場景有日誌記錄、性能測試、事務處理等。
私信小編007即可自動獲取大量Python視頻教程以及PDF電子書籍!
下面分幾個部分逐步介紹python中的裝飾器。
python如何理解函數
在介紹裝飾器之前,先介紹一下函數。理解python中的函數,首先要建立這樣認知:在python中,一切皆對象。變量、列表、字典,甚至函數、類、元類等都是對象。
這裡講的函數作為第一類對象,可以將它:
- 賦值給一個變量或存入其他數據結構,如列表、字典等
- 作為參數竄地給其他函數
- 作為函數的返回值
>>> def foo():
... i = 1
... print i
...
>>> a = foo
>>> a
>>> b = [str, foo]
>>> b
[, ]
>>> def bar(func):
... return func
...
>>> c = bar(foo)
>>> c
>>> c()
1
>>>
另外,實現了__call__方法類的實例也可以像函數一樣使用。
>>> class Bar:
... def __init__(self, i):
... self.i = i
... def __call__(self, j):
... return self.i + j
...
>>> foo = Bar(1)
>>> foo(2)
3
建立了以上的認知之後,我們來介紹裝飾器。
裝飾器其實是一種閉包
前面介紹過,閉包是一種引用了自由變量的函數。
>>> 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....
基本沒有修改什麼邏輯,只是把參數替換成了函數,就變成了一個簡單的裝飾器。所以,裝飾器其實是一種以函數作為參數的閉包。這個print_msg就是裝飾器,它封裝一些可複用的非業務邏輯,而被裝飾的foo可以專注於業務邏輯。這樣整個設計就非常清晰,而且增加了可讀性。
裝飾器的兩種類型
裝飾器有兩種類型:函數和類。
函數裝飾器,就像上面例子中一樣,是一個函數。但是裝飾器不僅可以是函數,還可以是類。類裝飾器在靈活性、內聚性、封裝型等方面優點更未突出。
前面看過了函數裝飾器的例子,下面看一個類裝飾器的例子
>>> 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="">
>>> a()
start....
hello
end....
參數設置
裝飾器參數
裝飾器的使用非常靈活,需要時可以設置必要的參數。
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
被裝飾函數參數
如果被裝飾函數需要傳入參數,可以在執行該函數的嵌套函數中設置。上面例子中,可以在printer中設置需要的相關參數。
def printer(*args, **kwargs):
if a == 1:
print('start....')
func(*args, **kwargs)
else:
func(*args, **kwargs)
@語法糖
@符號是裝飾器的語法糖,將@符號和裝飾器名稱放在被裝飾函數定義的地方,這樣在使用函數時不用顯示的調用裝飾器, 而且這樣並不會影響參數設置。
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
閱讀更多 編程夢工廠 的文章