1. 程式人生 > >函數裝飾器的擴展

函數裝飾器的擴展

str als tools 打印 art 裝飾器 裝飾 div before

一、函數裝飾器

1)帶參數的裝飾器:

import time
FLAGE = False
def timmer_out(flag):
    def timmer(func):
        def inner(*args,**kwargs):
            if flag:
                start = time.time()
                ret = func(*args,**kwargs)
                end = time.time()
                print(end-start)
                
return ret else: ret = func(*args, **kwargs) return ret return inner return timmer # timmer = timmer_out(FLAGE) @timmer_out(FLAGE) #wahaha = timmer(wahaha) def wahaha(): time.sleep(0.1) print(wahahahahahaha) @timmer_out(FLAGE) def erguotou(): time.sleep(
0.1) print(erguotoutoutou) wahaha() erguotou()

2)多個裝飾器裝飾同一個函數:

def wrapper1(func):
    def inner1():
        print(wrapper1 ,before func)
        ret = func()
        print(wrapper1 ,after func)
        return ret
    return inner1

def wrapper2(func):
    def inner2():
        print(wrapper2 ,before func
) ret = func() print(wrapper2 ,after func) return ret return inner2 def wrapper3(func): def inner3(): print(wrapper3 ,before func) ret = func() print(wrapper3 ,after func) return ret return inner3 @wrapper3 @wrapper2 @wrapper1 def f(): print(in f) return 哈哈哈 print(f()) #記錄用戶的登錄情況 #計算這個函數的執行時間

3)裝飾器的固定格式——wraps版:

from functools import wraps
def wrapper(func):  #func = holiday
    @wraps(func)
    def inner(*args,**kwargs):
        print(在被裝飾的函數執行之前做的事)
        ret = func(*args,**kwargs)
        print(在被裝飾的函數執行之後做的事)
        return ret
    return inner

@wrapper   #holiday = wrapper(holiday)
def holiday(day):
    ‘‘‘這是一個放假通知‘‘‘
    print(全體放假%s天%day)
    return 好開心

print(holiday.__name__)
print(holiday.__doc__)
ret = holiday(3)   #inner
print(ret)


# def wahaha():
#     ‘‘‘
#     一個打印娃哈哈的函數
#     :return:
#     ‘‘‘
#     print(‘娃哈哈‘)

# print(wahaha.__name__) #查看字符串格式的函數名
# print(wahaha.__doc__)  #document

函數裝飾器的擴展