话Python之装饰器(一)

一说装饰器,这是个啥,其实就是一个函数,新名字而已。

import time
from functools import wraps

def timethis(func):
    '''
    Decorator that reports the execution time.
    '''
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(func.__name__, end-start)
        return result
    return wrapper

@timethis
def countdown(n):
    while n>0:
        n -= 1

if __name__ == '__main__':
    countdown(100)

Ref:
https://python3-cookbook.readthedocs.io/zh_CN/latest/c09/p04_define_decorator_that_takes_arguments.html

猜你喜欢

转载自blog.csdn.net/woai8339/article/details/82152135