python裝飾器簡介及同時使用多個裝飾器的方法
python裝飾器簡介及同時使用多個裝飾器
裝飾器功能:
在不改變原有函數(shù)的情況下,唯已有函數(shù)添加新功能,且不改變函數(shù)名,無需改變函數(shù)的調(diào)用
特別適用于當多個函數(shù)需要添加相同功能時
python裝飾器常用于以下幾點:
- 登錄驗證
- 記錄日志
- 檢驗輸入是否合理
- Flask中的路由
什么是裝飾器呢?裝飾器如何使用?
# 聲明裝飾器
# 使用裝飾器的函數(shù),會自動將函數(shù)名傳入func變量中
def decorator(func):
def wrapper():
# 在func()函數(shù)外添加打印時間戳
print(time.time())
# 調(diào)用func(),實際使用中,該func就是使用裝飾器的函數(shù)
func()
return wrapper
# 使用裝飾器
# 使用裝飾器只需要在聲明函數(shù)前加上 @裝飾器函數(shù)名 即可
@decorator
def test():
print("this function' name is test")
# 使用裝飾器
@decorator
def hello():
print("this function' name is hello")
test()
hello()
# 運行結(jié)果
1587031347.2450945
this function' name is test
1587031347.2450945
this function' name is hello如果使用裝飾器的函數(shù)需要傳入?yún)?shù),只需改變一下裝飾器函數(shù)即可
對上面的函數(shù)稍微修改即可
def decorator(func):
def wrapper(arg):
print(time.time())
func(arg)
return wrapper
@decorator
def hello(arg):
print("hello , ",arg)
hello('武漢加油!')
# 輸出結(jié)果
1587031838.325085
hello , 武漢加油!
因為多個函數(shù)可以同時使用一個裝飾器函數(shù),考慮到各個函數(shù)需要的參數(shù)個數(shù)不同,可以將裝飾器函數(shù)的參數(shù)設(shè)置為可變參數(shù)
def decorator(func):
def wrapper(*args,**kwargs):
print(time.time())
func(*args,**kwargs)
return wrapper
@decorator
def sum(x,y):
print(f'{x}+{y}={x+y}')
sum(3,4)
# 運行結(jié)果
1587032122.5290427
3+4=7python支持一個函數(shù)同時使用多個裝飾器
同時使用多個裝飾器時,需要調(diào)用的函數(shù)本身只會執(zhí)行一次
但會依次執(zhí)行所有裝飾器中的語句
執(zhí)行順序為從上到下依次執(zhí)行
def decorator1(func):
def wrapper(*args, **kwargs):
print("the decoretor is decoretor1 !")
func(*args, **kwargs)
return wrapper
def decorator2(func):
def wrapper(*args, **kwargs):
print("the decoretor is decoretor2 !")
func(*args, **kwargs)
return wrapper
@decorator1
@decorator2
def myfun(func_name):
print('This is a function named :', func_name)
myfun('myfun')因為 @decorator1 寫在上面,因此會先執(zhí)行decorator1 中的代碼塊,后執(zhí)行decorator2 中的代碼塊
到此這篇關(guān)于python裝飾器簡介及同時使用多個裝飾器的文章就介紹到這了,更多相關(guān)python多個裝飾器使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Pytorch 實現(xiàn)凍結(jié)指定卷積層的參數(shù)
今天小編就為大家分享一篇Pytorch 實現(xiàn)凍結(jié)指定卷積層的參數(shù),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
Pycharm2020.1安裝中文語言插件的詳細教程(不需要漢化)
這篇文章主要介紹了Pycharm2020.1安裝中文語言插件的詳細教程,不需要漢化,本文給大家分享三種方法,在這小編推薦使用方法二,具體內(nèi)容詳情大家跟隨小編一起看看吧2020-08-08
matplotlib之Pyplot模塊繪制三維散點圖使用顏色表示數(shù)值大小
在撰寫論文時常常會用到matplotlib來繪制三維散點圖,下面這篇文章主要給大家介紹了關(guān)于matplotlib之Pyplot模塊繪制三維散點圖使用顏色表示數(shù)值大小的相關(guān)資料,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2022-08-08
用?Python?腳本實現(xiàn)電腦喚醒后自動拍照并截屏發(fā)郵件通知
這篇文章主要介紹了用?Python?腳本實現(xiàn)電腦喚醒后自動拍照并截屏發(fā)郵件通知,文中詳細的介紹了代碼示例,具有一定的 參考價值,感興趣的可以了解一下2023-03-03
python中使用iterrows()對dataframe進行遍歷的實例
今天小編就為大家分享一篇python中使用iterrows()對dataframe進行遍歷的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06
給Python學習者的文件讀寫指南(含基礎(chǔ)與進階)
今天,貓貓跟大家一起,好好學習Python文件讀寫的內(nèi)容,這部分內(nèi)容特別常用,掌握后對工作和實戰(zhàn)都大有益處,學習是循序漸進的過程,欲速則不達2020-01-01

