Python 装饰器是一种非常有用的功能,允许你修改或增强函数的行为,而无需修改函数本身的代码。装饰器广泛应用于各种场景,如权限校验、日志记录、性能监控等。
装饰器的基本概念
装饰器是一个接受函数作为参数并返回另一个函数的函数。简单来说,装饰器就是对函数进行包装的函数。
def my_decorator(func):
def wrapper():
print("装饰器执行了一些操作")
func()
print("装饰器执行了更多的操作")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
运行上述代码,输出结果为:
装饰器执行了一些操作
Hello!
装饰器执行了更多的操作
装饰器参数
装饰器可以接受参数,如下所示:
def my_decorator_with_args(a, b):
def wrapper(func):
def decorated_func():
print("参数 a 的值是:", a)
print("参数 b 的值是:", b)
func()
return decorated_func
return wrapper
@my_decorator_with_args(1, 2)
def say_hello():
print("Hello!")
say_hello()
运行上述代码,输出结果为:
参数 a 的值是: 1
参数 b 的值是: 2
Hello!
装饰器使用场景
- 日志记录:为函数添加日志记录功能。
- 性能监控:监控函数执行时间。
- 权限校验:校验用户是否有权限执行某个操作。
- 函数重载:实现类似函数重载的功能。
扩展阅读
更多关于 Python 装饰器的信息,可以参考 Python 装饰器详解。
[center]