Python中的装饰器

参考博客

【Python】一文弄懂python装饰器(附源码例子)

使用示例

1、基本装饰器

def simple_decorator(func):
    def wrapper():
        print("Before the function is called.")
        func()
        print("After the function is called.")
    return wrapper

@simple_decorator
def say_hello():
    print("Hello, World!")

say_hello()
Before the function is called.
Hello, World!
After the function is called.

@simple_decorator 等价于 say_hello = simple_decorator(say_hello)wrapper在调用 func的前后增加了额外的功能

2、带参数的装饰器

def decorator_with_args(func):
    def wrapper(name):
        print(f"Before calling {func.__name__}")
        func(name)
        print(f"After calling {func.__name__}")
    return wrapper

@decorator_with_args
def greet(name):
    print(f"Hello, {name}!")

greet("Alice")
Before calling greet
Hello, Alice!
After calling greet

wrapper 接收了 greet 的参数 name,并在调用 greet 前后添加了额外的逻辑

3、通用装饰器

def universal_decorator(func):
    def wrapper(*args, **kwargs):
        print(f"Function {func.__name__} is called with arguments {args} and {kwargs}")
        result = func(*args, **kwargs)
        print(f"Function {func.__name__} returned {result}")
        return result
    return wrapper

@universal_decorator
def add(a, b):
    return a + b

print(add(3, 5))
Function add is called with arguments (3, 5) and {}
Function add returned 8
8

wrapper 捕获了所有参数,并在调用 add 前后打印信息

4、带参数的装饰器

def repeat(times):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(times):
                func(*args, **kwargs)
        return wrapper
    return decorator

@repeat(3)
def say_hello():
    print("Hello!")

say_hello()
Hello!
Hello!
Hello!

@repeat(3) 等价于 say_hello = repeat(3)(say_hello)
repeat 接收参数 times,控制函数的执行次数

5、类方法装饰器

def method_decorator(func):
    def wrapper(self, *args, **kwargs):
        print(f"Calling method {func.__name__} of {self}")
        return func(self, *args, **kwargs)
    return wrapper

class Greeter:
    @method_decorator
    def greet(self, name):
        print(f"Hello, {name}!")

g = Greeter()
g.greet("Alice")
Calling method greet of <__main__.Greeter object at 0x...>
Hello, Alice!

6、装饰器链

def decorator_one(func):
    def wrapper(*args, **kwargs):
        print("Decorator One")
        return func(*args, **kwargs)
    return wrapper

def decorator_two(func):
    def wrapper(*args, **kwargs):
        print("Decorator Two")
        return func(*args, **kwargs)
    return wrapper

@decorator_one
@decorator_two
def say_hello():
    print("Hello!")

say_hello()
Decorator One
Decorator Two
Hello!

7、实际应用

import time

def timer(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"Function {func.__name__} took {end_time - start_time:.4f} seconds")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(2)
    print("Finished!")

slow_function()
Finished!
Function slow_function took 2.0001 seconds

装饰器常用于:

  1. 代码复用 :为多个函数添加相同的功能。
  2. 日志记录 :记录函数的调用信息。
  3. 性能监控 :统计函数的执行时间。
  4. 权限控制 :检查用户权限。
  5. 缓存 :存储函数的计算结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值