深入理解Python中的装饰器(Decorators)

在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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值