如何在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"{func.__name__}} executed in {end_time - start_time:.6f} seconds with result: {result}")
return result
return wrapper
@timer_decorator
def slow_function(n):
time.sleep(n)
return n
print(slow_function(2))
在这个例子中,timer_decorator
是一个装饰器函数,它接收一个函数作为参数,并返回一个新的函数。然后,我们定义了一个慢函数slow_function
并使用装饰器使其执行时间可记录。
还没有评论,来说两句吧...