python裝飾器:下邊幾個裝飾器帶參數和不帶參數例子詳解:
我們都知道,python中函數是可以被當做參數進行傳遞的,所以最直接的裝飾器實例如下:
①
def decorator(func):#裝飾器函數
print('welcome')
func()
print('end')
def test():
print('hello world')
#將test()方法以參數形式傳給方法decorator(func)
decorator(test)
#輸出結果:welcome
# hello world
# end
這樣寫比較麻煩,而且改變了源代碼的結構,容易出錯
可以使用裝飾器,把上例改爲:
②
def zhuangshiqi(func):
def decorator():
print('welcome')
func()
print('end')
return decorator
@zhuangshiqi
def test():
print('hello world')
test()
#打印結果welcome
# hello world
# end
裝飾器裝飾帶有參數的函數:
def decorator(func):
def wapper(*args,**kwargs):#存放被裝飾函數的參數
print('welcome')
return func(*args,**kwargs)
return wapper
@decorator
def test(n):
print(n*n)
test(3)
#打印結果
#welcome
#9
裝飾器和被裝飾函數都帶有參數:
def decrator(*dargs, **kargs):#接收裝飾器傳來的參數
def wrapper(func):
def _wrapper(*args, **kwargs):#存放被裝飾函數的參數
print(kargs)#打印爲一個字典
print(dargs)#打印爲一個元組
#你可以在這裏利用裝飾器的參數添加你想要的功能
return func(*args, **kwargs)
return _wrapper
return wrapper
@decrator(1,2,3,4,5,name='小明',age=18,height=180)
def test(x, y):
t=x*y
print(t)
test(2,3)#打印結果{'name': '小明', 'age': 18, 'height': 180}
# (1, 2, 3, 4, 5)
# 6