Python装饰器的理解与实现案例
Python装饰器是一种特殊类型的函数,它接受一个函数作为参数,并返回一个新的函数。这个新的函数在执行原功能的同时,可以添加额外的行为。
以下是一个简单的装饰器实现案例:
# 定义一个装饰器,表示打印函数执行前后的时间
def timer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs))
end_time = time.time()
print(f'Function {func.__name__}} execution time: {end_time - start_time} seconds')
return result
return wrapper
# 使用装饰器
@timer
def calculate_sum(numbers):
return sum(numbers)
numbers = [1, 2, 3]
result = calculate_sum(numbers)
print(result) # 输出:Function <function calculate_sum.<locals>.wrapper at 0x7f5d49e68>> execution time: 0.00016311072754 seconds
这个案例中,我们定义了一个timer
装饰器,它会记录并打印函数执行前后的时间。然后我们使用这个装饰器来装饰calculate_sum
函数。
还没有评论,来说两句吧...