欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python裝飾器簡介及同時(shí)使用多個(gè)裝飾器的方法

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

python裝飾器簡介及同時(shí)使用多個(gè)裝飾器

裝飾器功能:

在不改變原有函數(shù)的情況下,唯已有函數(shù)添加新功能,且不改變函數(shù)名,無需改變函數(shù)的調(diào)用
特別適用于當(dāng)多個(gè)函數(shù)需要添加相同功能時(shí)

python裝飾器常用于以下幾點(diǎn):

  • 登錄驗(yàn)證
  • 記錄日志
  • 檢驗(yàn)輸入是否合理
  • Flask中的路由

什么是裝飾器呢?裝飾器如何使用?

# 聲明裝飾器
# 使用裝飾器的函數(shù),會(huì)自動(dòng)將函數(shù)名傳入func變量中
def decorator(func):
    def wrapper():
        # 在func()函數(shù)外添加打印時(shí)間戳
        print(time.time())
        # 調(diào)用func(),實(shí)際使用中,該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()
# 運(yùn)行結(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 ,  武漢加油!
因?yàn)槎鄠€(gè)函數(shù)可以同時(shí)使用一個(gè)裝飾器函數(shù),考慮到各個(gè)函數(shù)需要的參數(shù)個(gè)數(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)
# 運(yùn)行結(jié)果
1587032122.5290427
3+4=7

python支持一個(gè)函數(shù)同時(shí)使用多個(gè)裝飾器

同時(shí)使用多個(gè)裝飾器時(shí),需要調(diào)用的函數(shù)本身只會(huì)執(zhí)行一次
但會(huì)依次執(zhí)行所有裝飾器中的語句
執(zhí)行順序?yàn)閺纳系较乱来螆?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')

因?yàn)?@decorator1 寫在上面,因此會(huì)先執(zhí)行decorator1 中的代碼塊,后執(zhí)行decorator2 中的代碼塊

到此這篇關(guān)于python裝飾器簡介及同時(shí)使用多個(gè)裝飾器的文章就介紹到這了,更多相關(guān)python多個(gè)裝飾器使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論