学习Python:装饰器

 应用场景:已经有一些现存稳定运行的函数,现在你需要加调试信息、运行时间或其他调试参数,这时不能去动已经稳定的函数,可以将函数名作为参数传到一个装饰器中,在该运行函数前后添加所需的代码。

import time

def timer(func):
    def wrapper(*args, **kw):
        start = time.time()
        func()
        end = time.time()
        used = end - start
        print(f'{func.__name__} used {used}')
    return wrapper

@timer
def step1():
    print('step1...')

@timer
def step2():
    print('step2...')

@timer
def step3():
    print('step3...')

step1()

https://blog.csdn.net/weixin_38632246/article/details/99694062

猜你喜欢

转载自blog.csdn.net/Stone_Wang_MZ/article/details/109534832