本片筆記學(xué)習(xí)自:Improve Your Python: Decorators Explained
首先需要知道的兩個(gè)點(diǎn):
1.函數(shù)可以作為參數(shù)
2.函數(shù)可以返回函數(shù)(生產(chǎn)函數(shù))前進(jìn)
Can we create a function that takes a function as a parameter and returns a function as the result. Would that be useful?
這樣我們就可以接收一個(gè)函數(shù)葡盗,然后將其封裝好后送出另外一個(gè)函數(shù)出去蜗细。
- 例子
def currency(f):
def wrapper(*args, **kwargs):
return '$' + str(f(*args, **kwargs))
return wrapper
在字符串之前加上’$‘。
@currency
def price_with_tax(self, tax_rate_percentage):
"""Return the price with *tax_rate_percentage* applied.
*tax_rate_percentage* is the tax rate expressed as a float, like "7.0"
for a 7% tax rate."""
return price * (1 + (tax_rate_percentage * .01))
加上語(yǔ)法糖侠仇,表示price_with_tax已經(jīng)被裝飾蓝撇,裝飾的方式在currency中定義崇决。
- 一點(diǎn)點(diǎn)的“副作用”
我們?cè)谘b飾的同時(shí)也將函數(shù)變成了price_with_tax,.name 和.doc都會(huì)是currency的颤枪,我們需要對(duì)裝飾器進(jìn)行一些修改:
from functools import wraps
def currency(f):
@wraps(f)
def wrapper(*args, **kwargs):
return '$' + str(f(*args, **kwargs))
return wrapper
- 威力
裝飾器的作用汗捡,一言以蔽之:
This notion of wrapping a function with additional functionality without changing the wrapped function is extremely powerful and useful.
Flask框架利用裝飾器來(lái)給不同的路徑添加不同的功能
@app.route('/')
def hello_world():
return 'Hello World!'
裝飾器可以添加參數(shù)的,下一次講類裝飾器再講畏纲。
看完下面你就知道裝飾器的形式了:
用處: