Python装饰器应用

装饰器基础

def timeit(func):
    def __(*args, **kwargs):
        t1 = time.time()
        ret = func(*args, **kwargs)
        t2 = time.time()
        print('call the function:%s spend time:%0.2f s' % (func.__name__, int((t2-t1))))
        return ret
    return __

@timeit
def func():
    print('Decorator')

func()
>>> Decorator
>>> call the function:func spend time:0.00 s

带参数的装饰器

def timeit(para1):
    def decorator(func):
        def __(*args, para1=para1,**kwargs):
            print(para1)
            t1 = time.time()
            ret = func(*args, **kwargs)
            t2 = time.time()
            print('call the function:%s spend time:%0.2f s' % (func.__name__, int((t2-t1))))
            return ret
        return __
    return decorator

@timeit('Para from decorator')
def func():
    print('Decorator')

>>> func()
>>> Para from decorator
>>> Decorator
>>> call the function:func spend time:0.00 s

装饰器参数在原函数中录入

实质是在里层函数新增参数,装饰器返回的是里层函数,

def timeit(para1, para2=None):
    def decorator(func):
        def __(*args, para1=para1,para2=para2, **kwargs):
            print(para1)
            print(para2)
            t1 = time.time()
            ret = func(*args, **kwargs)
            t2 = time.time()
            print('call the function:%s spend time:%0.2f s' % (func.__name__, int((t2-t1))))
            return ret
        return __
    return decorator

@timeit('Para from decorator')
def func():
    print('Decorator')

func(para2='Para2 from func')
>>> Para from decorator
>>> Para2 from func
>>> Decorator
>>> call the function:func spend time:0.00 s
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值