本篇是 Python 系列教程第 13 篇,更多内容敬请访问我的 Python 合集
Python 装饰器是一种强大的工具,用于修改或增强函数或方法的行为,而无需更改其源代码。装饰器本质上是一个接收函数作为参数的函数,并返回一个新的函数。装饰器的用途包括日志记录、性能测试、事务处理、缓存、权限校验等
1 基本语法
装饰器的基本语法是在函数定义之前使用@符号,紧跟着装饰器的名字。例如:
# 定义一个装饰器,参数为被装饰的方法
def my_decorator(func):
    def wrapper():
        print("方法运行前")
        func()
        print("方法运行后")
    return wrapper
# 用“@”使用装饰器
@my_decorator
def say_hello():
    print("Hello!")
say_hello()
这段代码会输出:
方法运行前
Hello!
方法运行后
2 参数传递
如果被装饰的函数需要参数,装饰器也需要相应地处理这些参数:
def my_decorator(func):
    def wrapper(name):
        print("方法运行前")
        func(name)
        print("方法运行后")
    return wrapper
@my_decorator
def greet(name):
    print(f"Hello, {name}!")
greet("Alice")
输出:
方法运行前
Hello, Alice!
方法运行后
参数可以用可变参数,比较灵活,如下:
def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("方法运行前")
        func(*args, **kwargs)
        print("方法运行后")
    return wrapper
@my_decorator
def greet(name):
    print(f"Hello, {name}!")
greet("Alice")
3 使用多个装饰器
你可以为同一个函数使用多个装饰器:
def decorator_A(func):
    print("enter A")
    def wrapper():
        print("Before A")
        func()
        print("After A")
    print("out A")
    return wrapper
 
def decorator_B(func):
    print("enter B")
    def wrapper():
        print("Before B")
        func()
        print("After B")
    print("out B")
    return wrapper
 
@decorator_A
@decorator_B
def my_function():
    print("Inside my_function")
 
# 执行被装饰器装饰的函数
my_function()
输出:
enter B
out B
enter A
out A
Before A
Before B
Inside my_function
After B
After A
注意打印结果的顺序。
为了方便表达我们先把靠近被修饰方法的装饰器叫内层装饰器,如示例中的@decorator_B,不靠近的叫外层装饰器,如示例中的@decorator_A。
在闭包wrapper外面的代码是内层装饰器先执行,在闭包wrapper内部的代码执行顺序复杂一些:①外层装饰器先执行func() 前面的代码->②内层装饰器执行func() 前面的代码->③执行func() ->④内层装饰器执行func() 后面的代码->⑤外层装饰器执行func() 后面的代码。
4 给装饰器传参
装饰器本身可以接受参数,可以根据传入的不同参数来改变装饰器的行为。
前面的例子都是没有参数的装饰器,如果我们想要给装饰器传参该怎么办呢?于是我们就思考一下,什么东东可以接收参数呢,答案是函数。bingo!Python也是这样设计的,我们只需要在装饰器外面包裹一层函数,就可以把参数传递给函数进而传递给装饰器了。
可以这样定义装饰器:
def repeat(num_times):
    def decorator_repeat(func):
        def wrapper(*args, **kwargs):
            for _ in range(num_times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator_repeat
@repeat(3)
def greet(name):
    print(f"Hello, {name}!")
greet("Alice")
输出:
Hello, Alice!
Hello, Alice!
Hello, Alice!
这样就定义了一个根据传入装饰器的数值执行指定次数函数的装饰器。
5 类作为装饰器
5.1 __call__方法
装饰器不仅仅可以是方法,也可以是类。这就不得不介绍一个特殊的方法__call__。
Python的类只要实现了__call__ 这个特殊方法,类的实例对象就可以像函数一样被调用,因为当尝试把对象写成方法调用的写法时(名称+()),Python 解释器会查找该对象的 __call__ 方法并调用它。
下面来看一个简单的例子,演示__call__的使用:
class Counter:
    def __init__(self):
        self.count = 0
    def __call__(self, *args, **kwargs):
        self.count += 1
        print(f"方法被调用了 {self.count} 次")
counter = Counter()
# 模拟调用
counter()
counter()
counter()
打印:
方法被调用了 1 次
方法被调用了 2 次
方法被调用了 3 次
5.2 类作为装饰器
类作为装饰器的一个主要优势是可以方便地维护状态,因为类可以有实例变量。
理解了__call__之后,我们可以想到类作为装饰器的原理是在类里实现了__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 say_hello(name):
    print(f"Hello, {name}!")
# 调用被装饰的函数
say_hello("Alice")
say_hello("Bob")
say_hello("Charlie")
# 输出
# say_hello 被调用了 1 次
# Hello, Alice!
# say_hello 被调用了 2 次
# Hello, Bob!
# say_hello 被调用了 3 次
# Hello, Charlie!
代码解释:
CallCounter类有一个构造函数__init__,它必须接受一个函数作为参数。- 类实现了 
__call__方法,这使得其实例可以像函数一样被调用。 - 在 
__call__方法中,每次调用被装饰的函数时,都会增加计数器count的值,并打印出函数被调用的次数。 - 最后,
__call__方法调用了原始函数self.func并返回结果。 









没有回复内容