亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

python裝飾器簡介及同時使用多個裝飾器的方法

 更新時間:2023年06月13日 11:34:05   作者:大數(shù)據(jù)老張  
這篇文章主要介紹了python裝飾器簡介及同時使用多個裝飾器的方法,python支持一個函數(shù)同時使用多個裝飾器,本文結(jié)合實例代碼給大家介紹的非常詳細,需要的朋友可以參考下

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=7

python支持一個函數(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)文章

最新評論