一、装饰器概述

  1. 装饰器允许开发者在不修改原函数代码的情况下,给函数添加额外的功能

  2. 装饰器本质上是一个返回函数的高阶函数

  3. 在 Python 中,使用装饰器语法糖 @ 可以便捷应用装饰器


二、函数概念

1、函数是一等对象
  1. 函数可以赋值给变量
def greet(name):
    return f"Hello, {name}"

my_func = greet

print(my_func("Alice"))
# 输出结果

Hello, Alice
  1. 函数可以作为参数传递
def greet(name):
    print(f"Hello, {name}")


def call_twice(func, arg):
    greet(arg)
    greet(arg)


call_twice(greet, "Alice")
# 输出结果

Hello, Alice
Hello, Alice
  1. 可以定义在另一个函数内部
def call_twice(arg):
    def greet(name):
        return f"Hello, {name}"

    print(greet(arg) + " " + greet(arg))


call_twice("Alice")
# 输出结果

Hello, Alice Hello, Alice
  1. 函数可以作为返回值
def get_func(flag):
    def add(num1, num2):
        return num1 + num2

    def subtract(num1, num2):
        return num1 - num2

    if flag == "+":
        return add
    elif flag == "-":
        return subtract


result_func = get_func("+")

result = result_func(10, 20)
print(result)
# 输出结果

30
2、闭包
  • 闭包是嵌套函数中,内部函数引用外部函数的变量,即使外部函数已经执行完毕

  • 如下例,函数 inner_func 引用了外部函数的变量 x,即使函数 outer_func 已经执行完,函数 closure 仍能访问 x

def outer_func(x):
    def inner_func(y):
        return x + y

    return inner_func


closure = outer_func(10)

result = closure(5)
print(result)
# 输出结果

15

三、装饰器手动实现

  1. 基本实现
# 装饰器函数
def my_decorator(func):
    def wrapper():
        print("函数执行前")
        result = func()
        print("函数执行后")
        return result

    return wrapper


# 原始函数
def say_hello():
    print("Hello")


# 应用装饰器
decorated_say_hello = my_decorator(say_hello)
decorated_say_hello()
# 输出结果

函数执行前
Hello
函数执行后
  1. 函数带参数
# 装饰器函数
def my_decorator(func):
    def wrapper(**kwargs):
        print("函数执行前")
        result = func(**kwargs)
        print("函数执行后")
        return result

    return wrapper


# 原始函数
def say_hello(name):
    print(f"Hello, {name}")


# 应用装饰器
decorated_say_hello = my_decorator(say_hello)
decorated_say_hello(name="Alice")
# 输出结果

函数执行前
Hello, Alice
函数执行后
  1. 装饰器带参数
# 装饰器函数
def my_decorator(func, times):
    def wrapper():
        print("函数执行前")
        for i in range(times):
            func()
        print("函数执行后")

    return wrapper


# 原始函数
def say_hello():
    print("Hello World")


# 应用装饰器
decorated_say_hello = my_decorator(say_hello, 3)
decorated_say_hello()
# 输出结果

函数执行前
Hello World
Hello World
Hello World
函数执行后

四、装饰器语法糖实现

  1. 基本实现
# 装饰器函数
def my_decorator(func):
    def wrapper():
        print("函数执行前")
        result = func()
        print("函数执行后")
        return result

    return wrapper


# 应用装饰器
@my_decorator
def say_hello():
    print("Hello")


say_hello()
# 输出结果

函数执行前
Hello
函数执行后
  1. 函数带参数
# 装饰器函数
def my_decorator(func):
    def wrapper(**kwargs):
        print("函数执行前")
        result = func(**kwargs)
        print("函数执行后")
        return result

    return wrapper


# 应用装饰器
@my_decorator
def say_hello(name):
    print(f"Hello, {name}")


say_hello(name="Alice")
# 输出结果

函数执行前
Hello, Alice
函数执行后
  1. 装饰器带参数
# 装饰器函数
def my_decorator(times):
    def decorator(func):
        def wrapper():
            print("函数执行前")
            for i in range(times):
                func()
            print("函数执行后")

        return wrapper

    return decorator


# 应用装饰器
@my_decorator(times=3)
def say_hello():
    print("Hello World")


say_hello()
# 输出结果

函数执行前
Hello World
Hello World
Hello World
函数执行后
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐