python装饰器

在 Python 中,装饰器是一种特殊的函数,用于在不改变原始函数代码的情况下增强或修改函数的功能。装饰器本质上是高阶函数,这意味着它们可以接收一个函数作为参数并返回一个新的函数。

装饰器的作用

  1. 代码重用:装饰器可以将通用的功能封装起来,应用于多个函数,从而避免代码重复。
  2. 增强函数功能:可以在函数执行前后添加额外的操作,比如日志记录、权限检查、输入验证等。
  3. 保持代码简洁:通过装饰器可以使代码更清晰、更易读,因为装饰器将附加功能从函数主体中分离出来。

基本示例

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

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

在这个示例中,@my_decoratorsay_hello 函数包裹在 wrapper 函数中,因此在 say_hello 调用前后会打印额外的信息。

其他常见装饰器

  • @staticmethod@classmethod:用于定义类的静态方法和类方法。
  • @property:将方法转换为只读属性。
  • @dataclass :自动生成类的基本方法,如 __init____repr__ 等。

各种 @ 装饰器的区别

  • 自定义装饰器:如上例所示,可以用于各种功能增强。
  • 内置装饰器
    • @staticmethod :定义静态方法,不需要实例作为第一个参数。

      python 复制代码
      class MyClass:
          @staticmethod
          def static_method():
              print("This is a static method")
    • @classmethod :定义类方法,接受类作为第一个参数。

      python 复制代码
      class MyClass:
          @classmethod
          def class_method(cls):
              print("This is a class method")
    • @property :将方法转换为属性,使用时不需要加括号。

      python 复制代码
      class MyClass:
          def __init__(self, value):
              self._value = value
      
          @property
          def value(self):
              return self._value
    • @dataclass :用于数据类,自动生成一些常用方法。

      python 复制代码
      from dataclasses import dataclass
      
      @dataclass
      class Person:
          name: str
          age: int

总结

装饰器是一种强大的工具,能够在不修改原始函数代码的情况下添加或修改功能。它们在代码重用、功能增强和保持代码简洁方面非常有用。内置装饰器如 @staticmethod@classmethod@property@dataclass 提供了特定的功能,帮助开发者更方便地定义和使用类的方法和属性。

相关推荐
databook17 小时前
Manim实现闪光轨迹特效
后端·python·动效
Juchecar18 小时前
解惑:NumPy 中 ndarray.ndim 到底是什么?
python
用户83562907805118 小时前
Python 删除 Excel 工作表中的空白行列
后端·python
Json_18 小时前
使用python-fastApi框架开发一个学校宿舍管理系统-前后端分离项目
后端·python·fastapi
数据智能老司机1 天前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机1 天前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i1 天前
drf初步梳理
python·django
每日AI新事件1 天前
python的异步函数
python