Python的装饰器有什么用?

2025-10发布8次浏览

Python的装饰器是一种设计模式,用于修改或增强函数或方法的行为。它们在许多高级编程任务中非常有用,如日志记录、访问控制、缓存、监控等。装饰器本质上是一个接受函数作为参数的函数,并返回一个新的函数。这个新的函数通常会扩展或修改原始函数的行为,然后返回结果。

装饰器的工作原理是通过使用@decorator_name语法来应用。例如,假设有一个简单的装饰器my_decorator,可以这样使用它:

def my_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

@my_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.

在这个例子中,my_decorator装饰了say_hello函数,在调用say_hello前后分别打印了消息。

装饰器还可以接受参数,这使得它们更加灵活。例如,一个简单的缓存装饰器可以存储函数的结果,并在下次调用时直接返回存储的结果,而不是重新计算:

def cache(func):
    cache_dict = {}
    def wrapper(*args):
        if args in cache_dict:
            return cache_dict[args]
        result = func(*args)
        cache_dict[args] = result
        return result
    return wrapper

@cache
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

print(fib(10))  # 计算并缓存结果
print(fib(10))  # 直接返回缓存的结果

装饰器还可以用于类方法和静态方法,以及类装饰器,用于修改类的行为。

装饰器在Python中非常强大和灵活,可以用于多种高级编程技巧。它们是Python编程中不可或缺的一部分。