深入理解Python中的装饰器
在 Python 中,装饰器(Decorator)是一种特殊类型的函数,它允许你修改或增强其他函数的功能,但又不改变原有函数的代码。
装饰器的工作原理如下:
定义一个装饰器函数,这个函数通常会接受一个被装饰的函数作为参数,并返回一个新的函数。
在需要修改或者增强功能的地方,使用 @ 装饰器来应用你之前定义的装饰器。
例如,一个简单的计时装饰器:
def time_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs))
end_time = time.time()
print(f'Function {func.__name__}} took '
f'{end_time - start_time} seconds')
return result
return wrapper
然后,你可以在需要计时的函数前使用 @time_decorator
装饰器:
@time_decorator
def slow_function():
time.sleep(5)
print('Slow function completed')
slow_function()
这样,每次调用 slow_function
时,都会自动记录并打印出执行时间。
还没有评论,来说两句吧...