python 裝飾器
傳參
被裝飾的函式帶有引數的情況
接上一篇,直接上程式碼
import time
def decorator(func):
def process(*args, **kwargs):
start = time.time()
func(*args, **kwargs)
end = time.time()
print(`函式func(也就是被裝飾的函式)的執行時間是:{}`.format(end-start))
return process
@decorator # python 裝飾器的正確使用,不需要傳參
def decorated():
time.sleep()
print(`decorated function`)
@decorator # python 裝飾器的正確使用,需要傳參
def decorated(key, val):
time.sleep()
print(`decorated function`)
# 此時不用再像上面一樣賦值,可以直接呼叫
decorated()
decorated(key, val)
</python>
返回值
被裝飾的函式有返回值在裝飾器內部需return被裝飾函式的呼叫
程式碼:
import time
def decorator(func):
def process(*args, **kwargs):
start = time.time()
return func(*args, **kwargs)
# end = time.time()
# print(`函式func(也就是被裝飾的函式)的執行時間是:{}`.format(end-start))
return process
@decorator # python 裝飾器的正確使用,不需要傳參
def decorated():
time.sleep()
print(`decorated function`)
return `來自不帶引數的被裝飾函式`
@decorator # python 裝飾器的正確使用,需要傳參
def decorated(key, val):
time.sleep()
print(`decorated function`)
return `來自帶有引數的被裝飾函式`
# 此時不用再像上面一樣賦值,可以直接呼叫
decorated()
decorated(key, val)
裝飾器帶引數
@decorator(val=“)
需要對裝飾期程式碼再包裝一層
程式碼
import time
def warpper(val_type):
def decorator(func):
def process(*args, **kwargs):
start = time.time()
return func(*args, **kwargs)
return process
return decorator
@decorator(val_type=``) # python 裝飾器的正確使用,不需要傳參
def decorated():
time.sleep()
print(`decorated function`)
return `來自不帶引數的被裝飾函式`
@decorator(val_type=``) # python 裝飾器的正確使用,需要傳參
def decorated(key, val):
time.sleep()
print(`decorated function`)
return `來自帶有引數的被裝飾函式`
# 此時不用再像上面一樣賦值,可以直接呼叫
decorated()
decorated(key, val)