Python进阶实例 第11例: 类装饰器 (Class Decorator)

除了函数,Python 中的类也可以用来实现装饰器。类装饰器通过实现 __call__ 方法,使实例对象可被调用,从而包装原始函数。


问题描述:

我们需要编写一个类装饰器,记录函数调用的次数,并在每次调用时打印调用次数。


代码示例:

class CallCounter:
    def __init__(self, func):
        self.func = func
        self.count = 0

    def __call__(self, *args, **kwargs):
        self.count += 1
        print(f"函数 {self.func.__name__} 第 {self.count} 次调用")
        return self.func(*args, **kwargs)

# 使用类装饰器
@CallCounter
def greet(name):
    print(f"Hello, {name}!")

# 调用函数
greet("Alice")
greet("Bob")
greet("Charlie")

步骤说明:

  1. __init__(self, func)
  2. 初始化时接收被装饰的函数 func,并保存下来。
  3. __call__ 方法
  4. 使类的实例变成可调用对象。
  5. 每次调用时执行计数逻辑,并调用原始函数。
  6. @CallCounter
  7. 使用类装饰器,相当于 greet = CallCounter(greet)。

运行结果:

函数 greet 第 1 次调用
Hello, Alice!
函数 greet 第 2 次调用
Hello, Bob!
函数 greet 第 3 次调用
Hello, Charlie!

总结:

  • 类装饰器适合需要 保存状态 的场景(如计数、缓存)。
  • 与函数装饰器相比,类装饰器更灵活,可以在类中定义多个方法和属性来扩展功能。
© 版权声明

相关文章

暂无评论

none
暂无评论...