Python装饰器真心好用

带返回值的装饰器

import time
def timer_used(f):
    def inner():
        startime = time.time()
        ret = f()
        endtime = time.time()
        print(f'耗时:{endtime - startime}  s')
        return ret
    return inner

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

ret = func1()
print(ret)
上一篇:04 一键查看服务器资源利用率


下一篇:LeetCode回溯算法