Python:装饰器

Python中的装饰器(Decorator)是一种设计模式,用于修改或增强函数、方法或类的行为,而不需要永久修改其结构。装饰器本质上是一个函数,它接受一个函数作为参数并返回一个新的函数。

以下是Python装饰器的关键特点和用法:

1. **基本结构**:

  装饰器是一个包装函数,用于扩展被装饰函数的功能。

  ```python

  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

  ```

2. **使用装饰器**:

  使用`@`语法将装饰器应用于函数。

  ```python

  @my_decorator

  def say_hello():

      print("Hello!")

  ```

3. **带参数的装饰器**:

  装饰器本身可以带有参数,这时需要使用嵌套函数结构。

  ```python

  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

  ```

4. **装饰器工厂**:

  返回装饰器的函数被称为装饰器工厂。

5. **装饰类**:

  装饰器也可以应用于类,它会修改类的`__init__`方法或其他方法。

  ```python

  def class_decorator(cls):

      print(f"Decorating class {cls.__name__}")

      return cls

  @class_decorator

  class MyClass:

      pass

  ```

6. **使用场景**:

  装饰器常用于日志记录、性能测试、事务处理、缓存、权限校验等场景。

7. **装饰器与高阶函数**:

  装饰器是高阶函数的一种应用,即函数的参数或返回值是另一个函数。

8. **装饰器的链式使用**:

  可以对一个函数应用多个装饰器,它们按照从近到远的顺序依次包装函数。

  ```python

  @decorator_one

  @decorator_two

  def my_function():

      pass

  ```

9. **保留原函数信息**:

  使用`functools.wraps`来保留原函数的名称、文档字符串等信息。

  ```python

  from functools import wraps

  def my_decorator(func):

      @wraps(func)

      def wrapper(*args, **kwargs):

          print("Before")

          func(*args, **kwargs)

          print("After")

      return wrapper

  ```

10. **类方法装饰器**:

    类方法装饰器需要在`wrapper`函数中使用`self`参数。

装饰器是Python中一个非常强大的工具,它提供了一种灵活、可重用的方式来修改函数或类的行为。通过使用装饰器,你可以使代码更加模块化、清晰和易于维护。

  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大连赵哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值