请解释Python中的装饰器(decorators)是什么,并举例说明其在实际编程中的应用。

装饰器是Python中一种高级特性,它允许程序员修改或拓展函数或类的行为,而无需直接更改函数或类的代码。装饰器本质上是接受一个函数作为参数的函数,并返回一个新的函数,新的函数通常会在执行原始函数前或后添加一些额外的功能。

装饰器的基本语法

装饰器的基本语法是在函数定义之前使用@decorator_name的形式来指定装饰器,其中decorator_name是你想要应用的装饰器的名称。

示例1:简单的装饰器

首先定义一个简单的装饰器,该装饰器的功能是在调用函数前和后打印一条消息:

import functools

def simple_decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print('函数调用前')
        result = func(*args, **kwargs)
        print('函数调用后')
        return result
    return wrapper

@simple_decorator
def say_hello(name):
    print(f'你好,{name}')

say_hello('小明')

输出结果将是:

函数调用前
你好,小明
函数调用后

示例2:带有参数的装饰器

有时候我们希望装饰器能够接受参数,以提供更灵活的功能。例如,一个用于记录函数执行时间的装饰器,并允许用户指定时间单位(秒或毫秒):

import time
import functools

def timing_decorator(units='s'):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            start_time = time.time()
            result = func(*args, **kwargs)
            end_time = time.time()
            elapsed = end_time - start_time
            if units == 'ms':
                elapsed *= 1000
            print(f'函数 {func.__name__} 执行时间: {elapsed:.2f} {units}')
            return result
        return wrapper
    return decorator

@timing_decorator(units='s')
def some_function():
    time.sleep(2)

some_function()

这段代码将输出:

函数 some_function 执行时间: 2.00 s

示例3:类装饰器

除了函数装饰器,Python中还可以使用类装饰器。类装饰器通常是用于实例化一个对象,该对象用来包装被装饰的函数或类。下面是一个简单的类装饰器示例,该装饰器记录函数的调用次数:

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'你好,{name}')

greet('小红')
greet('小明')

输出结果将是:

greet 已被调用了 1 次
你好,小红
greet 已被调用了 2 次
你好,小明

通过这些示例,我们可以看到装饰器在实际编程中的广泛应用,从简单的日志记录到复杂的权限验证,装饰器都是一个强大且灵活的工具。