一个有参装饰器,它可作用于任何函数上
2021-03-15 22:16
169 查看
最近Python网络班学员去一个公司面试,遇到了一个很有意思的问题:
请设计一个有参装饰器decorator,它可作用于任何函数上,要求可以接受一个int作为参数,该参数为要求的执行秒数,如果该函数的执行时间大于规定的执行秒数,请打印改函数名字和执行时间。
马哥教育Python网络班企业教练思路:
#我们先来分析下:1、有参数的装饰器 --> 可以使用高阶函数实现2、执行时间 --> 可以使用python的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)
代码执行结果:
the log take 5.030340194702148, less time<function log at 0x10216d950>
☆ END ☆
以上案例来自马哥Python网络班企业教练和学员的日常交流,学员学习Python过程中遇到问题不知道如何解决,遇到问题没有思路,都可以跟企业教练一对一交流,快来马哥教育了解一下Python课程吧。
相关文章推荐
- 请设计一个有参装饰器decorator,它可作用于任何函数上
- 学习装饰器,并设计一个装饰器,作用于函数上,打印函数执行时间-python
- 一个函数装饰器
- python装饰器实现原理?一个函数中怎么加入多个装饰器?怎么实现的?
- 使用函数指针,完成一个sort()函数,能对任何类型的数组元素进行排序: 回调函数 以及 memcpy ()原型实现
- Getchar函数从标准输入读取读取一个字符并返回它的值。如果输入中不再存在任何字符,函数就会返回常量EOF(在stdio.h中定义),用于提示文件的结尾。
- 写一个装饰器,查看函数执行的时间
- 任何一个函数中都有预定义的局部变量__func__
- 字符串参数必须包含一个或者多个数字,函数应该把这些数字字符转换为整数并返回这个整数。如果字符串参数包含了任何非数字字符,函数就返回零
- 如何用python的装饰器定义一个像C++一样的强类型函数
- 编写一个函数,作用是把一个char组成的字符串循环右移n个
- 编写程序删除一个字符串(不能使用任何操纵字符串的函数,不使用下标)
- 一个简单的装饰器算出函数运行时间
- 编写一个函数,作用是把一个char组成的字符串循环右移n个
- 编写一个函数,作用是把一个char组成的字符串循环右移n个。比如原来是“abcdefghi”如果n=2,移位后应该是“hiabcdefgh”
- Python:有参装饰器与多个装饰器装饰一个函数
- 带函数的装饰器、多个装饰器装饰一个函数
- C 这个字符串参数必须包含一个或者多个数字,函数应该把这些数字字符转换为整数并返回这个整数。如果字符串参数包含了任何非数字字符,函数就返回零。
- 多个装饰器装饰一个函数
- 一个小例子理解全局作用域和函数作用域