Python装饰器真心好用

带万能参数、带返回值的装饰器

import time
def timer_used(f):
    def inner(*args,**kwargs):#将参数聚合
        startime = time.time()
        ret = f(*args,**kwargs)#参数打散
        endtime = time.time()
        print(f'耗时:{endtime - startime}  s')
        return ret
    return inner

@timer_used
def func1(n):
    time.sleep(0.05)
    print(f'welcome {n} to my world' )
    return {'name':'猪小气'}
@timer_used
def func2(name,age):
    time.sleep(0.1)
    print(f'{age}岁的{name}bye-bye')
    return 999

ret = func1('老朋友')
func2('猪小气',18)

posted on 2021-06-26 18:19  猪小气  阅读(51)  评论(2编辑  收藏  举报