python中裝飾器的使用
阿新 • • 發佈:2019-01-06
python中裝飾器的使用
裝飾器在不改變函式的原有程式碼的前提下給函式新增新的功能,是程式開發中經常會用到的一個功能,用好了裝飾器,開發效率如虎添翼。
一、裝飾器的作用
- 引入日誌
- 函式執行時間統計
- 執行函式前預備處理
- 執行函式後清理功能
- 許可權校驗等場景
- 快取
二、裝飾器示例
例1. 無引數的函式
import time def time_fun(func): def wrapped_func(): print("%s called at %s" % (func.__name__, time.ctime())) func() return wrapped_func @time_fun def foo(): print("I am foo") foo()
輸出結果:
foo called at Wed Sep 26 10:14:06 2018
I am foo
上面程式碼理解裝飾器執行行為可理解成(重點理解)
foo = time_fun(foo)
# foo先作為引數賦值給func後,foo接收指向timefun返回的wrapped_func
foo()
# 呼叫foo(),即等價呼叫wrapped_func()
# 內部函式wrapped_func被引用,所以外部函式的func變數(自由變數)並沒有釋放
# func裡儲存的是原foo函式物件
例2. 被裝飾的函式有引數
import time def time_fun(func): def wrapped_func(a, b): print("%s called at %s" % (func.__name__, time.ctime())) func(a, b) return wrapped_func @time_fun def foo(a, b): print(a+b) foo(3, 5)
輸出結果:
foo called at Wed Sep 26 10:11:54 2018
8
例3. 被裝飾的函式有不定長引數
import time def time_fun(func): def wrapped_func(*args, **kwargs): print("%s called at %s"%(func.__name__, time.ctime())) func(*args, **kwargs) return wrapped_func @time_fun def foo(a, b, c): print(a+b+c) foo(2, 4, 6)
輸出結果:
foo called at Wed Sep 26 10:17:22 2018
12
例4. 裝飾器中的return
import time
def time_fun(func):
def wrapped_func():
print("%s called at %s" % (func.__name__, time.ctime()))
return func()
return wrapped_func
@time_fun
def foo():
print("I am foo")
@time_fun
def getInfo():
return '---test---'
foo()
time.sleep(2)
getinfo = getInfo()
time.sleep(2) # 測試用,這個時候並未輸出'---test---'
print(getinfo)
輸出結果:
foo called at Wed Sep 26 10:30:37 2018
I am foo
getInfo called at Wed Sep 26 10:30:39 2018
---test---
- 總結:
一般情況下為了讓裝飾器更通用,可以有return