Discuss / Python / 耗时2天去搞懂闭包和装饰器,越到后面越难懂了

耗时2天去搞懂闭包和装饰器,越到后面越难懂了

Topic source

SherryMaoMAO

#1 Created at ... [Delete] [Delete and Lock User]
# !/usr/bin/env python
# -*- coding: UTF-8 -*-
# 请设计一个decorator,它可作用于任何函数上,并打印该函数的执行时间:
import time, functools
def metric(fn):
    @functools.wraps(fn)
    def wrapper(*args, **kw):
        print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
        print('%s executed in %s ms' % (fn.__name__, 10.24))
        return fn(*args, **kw)
    return wrapper

SherryMaoMAO

#2 Created at ... [Delete] [Delete and Lock User]

执行时间用错函数,代码修改为:

# !/usr/bin/env python# -*- coding: UTF-8 -*-# 请设计一个decorator,它可作用于任何函数上,并打印该函数的执行时间:import time, functoolsdef metric(fn):    @functools.wraps(fn)    def wrapper(*args, **kw):        time_start = time.time()        fn(*args, **kw)        time_end = time.time()        print('%s executed in %s ms' % (fn.__name__, (time_end - time_start)))        return fn(*args, **kw)    return wrapper

  • 1

Reply