一、前置说明
1、总体目录
2、相关回顾
3、本节目标
- 了解 Python 装饰器基础
二、主要内容
装饰器(Decorators)是 Python 中一种强大而灵活的功能,它允许你在不修改原始函数代码的情况下,动态地修改或增强函数的行为。
1、基本概念
装饰器 是一种特殊的函数,用来包装或修改其他函数的行为。
生活中的例子:
想象一栋新房子的主体装修已经完成,已经具备了居住功能,在这个基础上需要给这个房子做一些额外装饰,比如添置挂画、摆件等。你可以把这个装饰的过程看作是一个装饰器。
2、基本原理
装饰器本质上是一个函数,它接受一个函数作为输入,并返回一个新的函数。在这个过程中,可以在新函数中添加额外的功能,或者修改原始函数的行为。
3、核心作用
- 代码重用:装饰器可以用于包装通用的功能,使其能够被多个函数共享。
- 代码增强:通过装饰器在不改变原始函数结构的情况下,为其增加额外的功能。
- 面向切面编程:装饰器允许在不修改函数代码的情况下,将横切关注点(如日志、性能监控)从业务逻辑中分离出来。
4、Demo示例
示例1:基本装饰器
def simple_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
@simple_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.
使用 @decorator 语法糖 时,解释器会自动将下方的函数传递给装饰器,并将返回的结果重新赋值给原函数名。使用 @simple_decorator 装饰下方的 say_hello 函数,等效于:say_hello = simple_decorator(say_hello),这样可以在不改变原函数调用方式的情况下应用装饰器。
示例2:带参数的装饰器
def decorator_with_args(arg):
    def actual_decorator(func):
        def wrapper(*args, **kwargs):
            print(f"Decorator argument: {arg}")
            for i in range(arg):
                func(*args, **kwargs)
        return wrapper
    return actual_decorator
@decorator_with_args(3)
def greet(name):
    print(f"Hello, {name}!")
greet("Alice")
输出结果:
Decorator argument: 3
Hello, Alice!
Hello, Alice!
Hello, Alice!
示例3:多个装饰器
def decorator1(func):
    def wrapper1():
        print("Decorator 1")
        func()
    return wrapper1
def decorator2(func):
    def wrapper2():
        print("Decorator 2")
        func()
    return wrapper2
@decorator1
@decorator2
def my_function():
    print("Original function")
my_function()
输出结果:
Decorator 1
Decorator 2
Original function
三、后置说明
1、要点小结
- 装饰器本质上是一个函数,它接受一个函数作为输入,并返回一个新的函数。
- 装饰器的核心作用是在不改变原函数结构的情况下,扩展额外的功能。
- 按实际需要,可编写带参数的装饰器和不带参数的装饰器。
2、下节准备
- Python 装饰器执行过程详解
