装饰器理解与应用:编写一个Python装饰器示例。
装饰器在Python中是一种特殊类型的函数,它允许你修改其他函数的功能,而无需改变这些函数的原始代码。
下面是一个简单的Python装饰器示例,这个装饰器用于计算函数执行的时间:
import time
def timer_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs))
end_time = time.time()
print(f"Function {func.__name__}} executed in {end_time - start_time} seconds")
return result
return wrapper
@timer_decorator
def slow_function():
time.sleep(2)
slow_function()
在这个例子中,timer_decorator
就是一个装饰器,它接受一个函数作为参数,并返回一个新的函数。新函数在执行原函数的同时,还会计算并打印出执行时间。
还没有评论,来说两句吧...