请解释Python中的装饰器(Decorator)如何实现代码复用,并举例说明其在模块化设计中的应用场景。

在Python中,装饰器(Decorator)是一种高级功能,允许在不修改原函数代码的情况下,动态增强函数的行为。装饰器的核心思想是通过嵌套函数或类的方式实现代码复用,通常用于日志记录、性能测试、权限验证等场景。装饰器的语法是通过@符号实现的,它的本质是一个接受函数作为参数并返回函数的函数。

装饰器的实现原理

装饰器的实现依赖于Python的函数是一等对象的特性,即函数可以作为参数传递,也可以作为返回值。装饰器的基本结构如下:

def decorator(func):
    def wrapper(*args, **kwargs):
        # 在调用原函数前的逻辑
        result = func(*args, **kwargs)
        # 在调用原函数后的逻辑
        return result
    return wrapper

装饰器的应用示例

场景1:日志记录

假设我们需要记录函数的调用信息,可以定义一个日志装饰器:

def log_decorator(func):
    def wrapper(*args, **kwargs):
        print(f"Calling function: {func.__name__}")
        print(f"Arguments: {args}, {kwargs}")
        result = func(*args, **kwargs)
        print(f"Function {func.__name__} finished")
        return result
    return wrapper

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

print(add(2, 3))

输出结果:

Calling function: add
Arguments: (2, 3), {}
Function add finished
5

场景2:性能测试

我们可以通过装饰器测量函数的执行时间:

import time

def timeit_decorator(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} seconds")
        return result
    return wrapper

@timeit_decorator
def slow_function():
    time.sleep(2)
    return "Done"

print(slow_function())

输出结果:

Function slow_function took 2.000114917755127 seconds
Done

装饰器在模块化设计中的应用

在模块化设计中,装饰器可以将通用的功能(如日志、权限检查)与业务逻辑分离,从而实现高内聚低耦合的设计目标。例如,在Web框架中,可以通过装饰器实现路由注册或权限验证:

routes = {}

def route(path):
    def decorator(func):
        routes[path] = func
        return func
    return decorator

@route("/home")
def home():
    return "Welcome to the home page"

@route("/about")
def about():
    return "About us"

print(routes)

输出结果:

{'/home': <function home at 0x7f8c1c1b70d0>, '/about': <function about at 0x7f8c1c1b7160>}

通过装饰器,我们能够将路由注册逻辑从视图函数中分离出来,使得代码更加清晰和易于维护。