装饰器的进阶

from functools import wraps     #functools.wraps  防止一些函数返回值失效
def wrapper(func):
    @wraps(func)                #加在最内层函数正上方
    def inner():
        '''执行函数之前要做的'''
        ret =func(*args,**kwargs)
        '''执行函数之后要做的'''
        return ret
    return inner
    
@wrapper 
def holiday(day):
    '''这是一个放假通知'''
    print('全体放假$s天'%day)
    return '好开心'

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

 

带参数的装饰器

#多层装饰器
import time      #模块调用
FLAGE = True              # FLAGE = Flase
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_out(FLAGE)
def wahaha():
    time.time(0.1)
    print('wahahahahahaha')

@timmer_out(FLAGE)
def niuniu():
    time.sleep(0.1)
    print('niuniuniubility')

wahaha()
niuniu()

三层装饰器

def wrapper1(func):        #func-->f
    def inner():
        print('wrapper1 ,before func')
        func()        #f()
        print('wrapper1 ,after func')
    return inner

def wrapper2(func):    #func-->inner
    def inner():
        print('wrapper2 ,before func')
        func()         #inner1()
        print('wrapper2 ,after func')
    return inner

@wrapper2            #f = wrapper2(f) = wrapper2(inner1) = inner2
@wrapper1          #f = wrapper1(f) = inner
def f():
    print('in f')
f()                    inner2()

 

posted on 2017-12-29 14:55  Kindergarten_Panda  阅读(129)  评论(0编辑  收藏  举报