在Python中,装饰器是一种非常强大且优雅的语法结构,它允许我们在不修改原有函数代码的情况下,给函数增加新的功能。装饰器广泛应用于日志记录、性能测试、事务处理、权限校验等场景。
基本概念
装饰器本质上是一个函数,它接收一个函数作为参数并返回一个新的函数。这个新的函数通常会在原函数执行前后添加一些额外的功能。
简单装饰器示例
python复制代码
def my_decorator(func): | |
def wrapper(): | |
print("Something is happening before the function is called.") | |
func() | |
print("Something is happening after the function is called.") | |
return wrapper | |
@my_decorator | |
def say_hello(): | |
print("Hello!") | |
say_hello() | |
# 输出: | |
# Something is happening before the function is called. | |
# Hello! | |
# Something is happening after the function is called. |
带参数的装饰器
如果原函数需要参数,装饰器需要稍作修改以支持这些参数。
python复制代码
def my_decorator(func): | |
def wrapper(*args, **kwargs): | |
print("Something is happening before the function is called.") | |
result = func(*args, **kwargs) | |
print("Something is happening after the function is called.") | |
return result | |
return wrapper | |
@my_decorator | |
def add(a, b): | |
return a + b | |
print(add(5, 3)) | |
# 输出: | |
# Something is happening before the function is called. | |
# Something is happening after the function is called. | |
# 8 |
使用类作为装饰器
除了函数,类也可以用作装饰器。当使用类作为装饰器时,__call__
方法会被自动调用。
python复制代码
class MyDecorator: | |
def __init__(self, func): | |
self.func = func | |
def __call__(self, *args, **kwargs): | |
print("Something is happening before the method is called.") | |
result = self.func(*args, **kwargs) | |
print("Something is happening after the method |