python中的装饰器

装饰器(Decorator)是 Python 中的一种语法糖,它允许你修改或增强函数或类的行为。下面详细解释:

  1. 基本概念
    装饰器本质上是一个函数,它接受一个函数作为参数,并返回一个新的函数:
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.
  1. 带参数的装饰器
def log_execution_time(func):
    def wrapper(*args, **kwargs):
        import time
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"Function {func.__name__} took {end_time - start_time} seconds")
        return result
    return wrapper

@log_execution_time
def calculate_sum(n):
    return sum(range(n))

# 使用
result = calculate_sum(1000000)
  1. 实际应用示例
    a、计时装饰器:
def timer(func):
    def wrapper(*args, **kwargs):
        import time
        start = time.time()
        result = func(*args, **kwargs)
        print(f"Function {func.__name__} took {time.time() - start:.2f} seconds")
        return result
    return wrapper

@timer
def slow_function():
    import time
    time.sleep(1)

2、缓存装饰器:


2. **缓存装饰器**:
```python
def cache(func):
    _cache = {}
    def wrapper(*args):
        if args not in _cache:
            _cache[args] = func(*args)
        return _cache[args]
    return wrapper

@cache
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

c、权限检查装饰器:

def require_auth(func):
    def wrapper(*args, **kwargs):
        if not is_authenticated():  # 假设有这个函数
            raise Exception("Authentication required")
        return func(*args, **kwargs)
    return wrapper

@require_auth
def sensitive_operation():
    print("Performing sensitive operation")
  1. 类装饰器
class CountCalls:
    def __init__(self, func):
        self.func = func
        self.count = 0
    
    def __call__(self, *args, **kwargs):
        self.count += 1
        print(f"Call {self.count} of {self.func.__name__}")
        return self.func(*args, **kwargs)

@CountCalls
def say_hello():
    print("Hello!")
  1. 多个装饰器
def bold(func):
    def wrapper():
        return "<b>" + func() + "</b>"
    return wrapper

def italic(func):
    def wrapper():
        return "<i>" + func() + "</i>"
    return wrapper

@bold
@italic
def greet():
    return "Hello!"

# 输出:<b><i>Hello!</i></b>

装饰器是 Python 中非常强大的特性,可以用来:

  • 添加日志
  • 性能测量
  • 访问控制
  • 缓存
  • 参数验证

等多种用途。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值