首页 > 其他 > 详细

请设计一个有参装饰器decorator,它可作用于任何函数上

时间:2020-03-03 09:02:30      阅读:62      评论:0      收藏:0      [点我收藏+]
最近有小伙伴面试,遇到一个很有意思的题:
请设计一个有参装饰器decorator,它可作用于任何函数上,要求可以接受一个int作为参数,该参数为要求的执行秒数,如果该函数的执行时间大于规定的执行秒数,请打印改函数名字和执行时间。

这个题我之前面试的也遇到过,当时用高阶函数的方式实现,现在又遇到了,废话少说,咱们开发。

先来分析下:

1 有参数的装饰器 --> 高阶函数

2 执行时间 --> time 库

上代码:

from functools import wraps
import time

# 面向对象写法
class TakeTime:
    def __init__(self, para: int):
        self.para = para

    def __call__(self, func):
        @wraps(func)
        def wrapped(*args, **kwargs):
            start_time = time.time()
            name = func.__name__
            func(*args, **kwargs)
            count_time = time.time() - start_time
            if self.para >= count_time:
                print("the {name} take {time}, less time".format(name=name, time=count_time))
            else:
                print("the {name} take {time}, more time".format(name=name, time=count_time))
            return func
        return wrapped

# 常规写法
def func_time(para: int):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            start_time = time.time()
            name = func.__name__
            func(*args, **kwargs)
            count_time = time.time() - start_time
            if para >= count_time:
                print("the {name} take {time}, less time".format(name=name, time=count_time))
            else:
                print("the {name} take {time}, more time".format(name=name, time=count_time))
            return func
        return wrapper
    return decorator

@TakeTime(10)
def log():
    for x in range(10):
        time.sleep(0.5)

@func_time(10)
def log1():
    for x in range(10):
        time.sleep(0.5)

请设计一个有参装饰器decorator,它可作用于任何函数上

原文:https://blog.51cto.com/14730644/2474992

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!