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 提供了特定的功能,帮助开发者更方便地定义和使用类的方法和属性。

相关推荐
zone773913 小时前
001:简单 RAG 入门
后端·python·面试
F_Quant13 小时前
🚀 Python打包踩坑指南:彻底解决 Nuitka --onefile 配置文件丢失与重启报错问题
python·操作系统
允许部分打工人先富起来14 小时前
在node项目中执行python脚本
前端·python·node.js
IVEN_14 小时前
Python OpenCV: RGB三色识别的最佳工程实践
python·opencv
haosend15 小时前
AI时代,传统网络运维人员的转型指南
python·数据网络·网络自动化
曲幽15 小时前
不止于JWT:用FastAPI的Depends实现细粒度权限控制
python·fastapi·web·jwt·rbac·permission·depends·abac
IVEN_1 天前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang1 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮1 天前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling1 天前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python