狂自私

导航

python装饰器是什么?有什么作用?

Python 装饰器

装饰器是 Python 中的一种特殊语法结构,允许在运行时动态地修改或增强函数或方法的行为。它们通常用来添加功能,而不需要直接修改原始函数的代码。

作用

  1. 代码重用

    • 装饰器可以封装一些通用的功能,比如日志记录、权限检查、性能监控等,可以在多个函数之间共享这些功能,而不需要重复代码。
  2. 增强功能

    • 装饰器可以在调用原始函数之前或之后执行一些额外的操作,如输入验证、输出格式化等,增强原始函数的功能。
  3. 分离关注点

    • 装饰器帮助将核心业务逻辑与辅助功能(如日志、错误处理)分离,使代码更清晰、更易于维护。
  4. 简化函数调用

    • 通过装饰器,可以简化对某些常见功能的调用,如缓存结果、重试机制等,无需在每个函数中实现相同的逻辑。

装饰器的基本语法

一个简单的装饰器通常是一个接受一个函数作为参数,并返回一个新函数的函数。

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.

关键点

  1. @语法

    • 使用 @decorator_name 语法将装饰器应用到一个函数上,等价于 say_hello = my_decorator(say_hello)
  2. 接受参数的装饰器

    • 如果你需要为装饰器传递参数,可以创建一个装饰器生成器。
    def repeat(num_times):
        def decorator_repeat(func):
            def wrapper(*args, **kwargs):
                for _ in range(num_times):
                    func(*args, **kwargs)
            return wrapper
        return decorator_repeat
    
    @repeat(num_times=3)
    def greet(name):
        print(f"Hello, {name}!")
    
    greet("Alice")
    

    输出:

    Hello, Alice!
    Hello, Alice!
    Hello, Alice!
    
  3. 使用 functools.wraps

    • 当你使用装饰器时,原始函数的元数据(如名称、文档字符串等)可能会丢失。可以使用 functools.wraps 来保留这些信息。
    from functools import wraps
    
    def my_decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            print("Before calling the function")
            return func(*args, **kwargs)
        return wrapper
    

总结

Python 装饰器是一个强大的工具,可以用于函数和方法的动态修改和增强。它们不仅可以提高代码的可读性和可维护性,还能促进代码重用。理解如何创建和使用装饰器是 Python 编程中的重要技能。

posted on 2024-09-12 09:02  狂自私  阅读(179)  评论(0)    收藏  举报