装饰器是一种函数,它允许你动态地修改函数或类的行为。它接受一个函数作为参数,并返回一个新的函数或修改原来地函数。
装饰器的语法使用 @decorator_name 来应用在函数或方法上。
Python还提供了一些内置的装饰器,比如@staticmethod 和 @classmethod 用于定义静态方法和类方法。
装饰器的应用场景:日志记录 、 性能分析、 权限控制 缓存
使用装饰器
装饰器通过@符号应用在函数定义之前,例如:
@time_logger
def target_function():
pass
def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(n):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3) #带参数的装饰器
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
class DecoratorClass:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
# 在调用原始函数之前/之后执行的代码
result = self.func(*args, **kwargs)
# 在调用原始函数之后执行的代码
return result
@DecoratorClass #类装饰器,包含_call_方法的类
def my_function():
pass