1.Decorator 修饰器的定义

Decorator 修饰器是一种在不修改原有函数的情况下,增加新功能的一种设计模式。它是一种特殊的函数,用于包装其他函数,以便在调用原函数之前或之后做一些额外的操作。Decorator 修饰器有助于减少代码重复,提高代码可读性和可维护性,提高程序的可扩展性。

2.Decorator 修饰器的使用

Decorator 修饰器的使用有两种方法:

1)使用@符号,将修饰器函数作为参数传递给原函数,如:

@decorator_func
def func(param):
pass
Python

2)使用函数装饰器,将原函数作为参数传递给修饰器函数,如:

def decorator_func(func):
def wrapper(param):
pass
return wrapper
func = decorator_func(func)
Python

3.Decorator 修饰器的应用

Decorator 修饰器可以应用于记录函数运行时间、检查函数参数、缓存函数结果、检查用户权限等功能。下面是一个简单的应用实例:

import time
def time_decorator(func):
def wrapper(*args, **kwargs):
start = time.time()
res = func(*args, **kwargs)
end = time.time()
print("函数运行时间:{}s".format(end-start))
return res
return wrapper

@time_decorator
def foo():
time.sleep(2)
print("foo函数调用完毕")

if __name__ == '__main__':
foo()
Python

运行结果:

foo 函数调用完毕
函数运行时间:2.0014400482177734s
Python