当前位置: 首页 > article >正文

【Python知识宝库】Python中的装饰器:优雅地扩展函数功能


在这里插入图片描述

🎬 鸽芷咕:个人主页

 🔥 个人专栏: 《C++干货基地》《粉丝福利》

⛺️生活的理想,就是为了理想的生活!

文章目录

  • 前言
    • 一、装饰器的定义
    • 二、使用装饰器
    • 三、自定义装饰器
      • 1. 有参数的函数装饰器
      • 2. 装饰器链
    • 四、装饰器的进阶用法
      • 1. 使用`functools.wraps`
      • 2. 装饰器工厂
    • 五、总结

前言

Python中的装饰器是一种特殊的函数,它们可以用来修改其他函数的功能。装饰器本质上是一个返回函数的函数,它们允许我们在不修改原始函数代码的情况下,添加额外的功能。本文将介绍Python中装饰器的使用,以及如何创建和使用自定义装饰器。

一、装饰器的定义

装饰器是一种特殊的函数,它们接受一个函数作为参数,并返回一个新的函数。装饰器通常用来在运行时动态地给函数添加功能。

def 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

二、使用装饰器

使用装饰器非常简单,你只需要将装饰器应用于你想要修改的函数上。

@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. 有参数的函数装饰器

如果被装饰的函数接受参数,你需要在装饰器内部创建一个包装函数来接收这些参数。

def repeat decorater(func):
    def wrapper(*args, **kwargs):
        print("Something is happening before the function is called.")
        result = func(*args, **kwargs)
        print("Something is happening after the function is called.")
        return result
    return wrapper
@repeat
def greet(name):
    print(f"Hello, {name}!")
greet("Alice")
# 输出:
# Something is happening before the function is called.
# Hello, Alice!
# Something is happening after the function is called.

2. 装饰器链

装饰器可以叠加使用,形成一个装饰器链。每个装饰器都会对函数进行一层包装。

def debug(func):
    def wrapper(*args, **kwargs):
        print(f"Calling function: {func.__name__}")
        return func(*args, **kwargs)
    return wrapper
@debug
@repeat
def greet(name):
    print(f"Hello, {name}!")
greet("Bob")
# 输出:
# Calling function: greet
# Something is happening before the function is called.
# Hello, Bob!
# Something is happening after the function is called.

四、装饰器的进阶用法

1. 使用functools.wraps

为了保留原始函数的元信息(如文档字符串和名字),可以使用functools.wraps装饰器。

from functools import wraps
def decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print("Something is happening before the function is called.")
        result = func(*args, **kwargs)
        print("Something is happening after the function is called.")
        return result
    return wrapper
@decorator
def greet(name):
    """Greet the person with their name."""
    print(f"Hello, {name}!")
print(greet.__name__)  # 输出: greet
print(greet.__doc__)   # 输出: Greet the person with their name.

2. 装饰器工厂

装饰器工厂是一个返回装饰器的函数,它可以接受参数来定制装饰器的行为。

def decorator_factory(prefix):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            print(f"{prefix}: Before calling {func.__name__}")
            result = func(*args, **kwargs)
            print(f"{prefix}: After calling {func.__name__}")
            return result
        return wrapper
    return decorator
@decorator_factory("DEBUG")
def greet(name):
    print(f"Hello, {name}!")
greet("Charlie")
# 输出:
# DEBUG: Before calling greet
# Hello, Charlie!
# DEBUG: After calling greet

五、总结

Python中的装饰器是一种强大且优雅的工具,它们允许我们在不修改原始函数的情况下扩展函数的功能。通过使用装饰器,我们可以编写出更加清晰、可维护的代码。本文介绍了装饰器的定义、使用、自定义以及进阶用法,希望这些内容能够帮助你更好地理解和利用Python中的装饰器。


http://www.kler.cn/news/302222.html

相关文章:

  • 有关 Element-ui 的一些思考
  • 连接数据库(以MySQL为例)
  • Android Framework(五)WMS-窗口显示流程——窗口布局与绘制显示
  • python清除一个月以前的ES索引文档数据
  • 单片机组成原理
  • C语言——静态链表和动态链表
  • 小红书品牌商家怎么接入三方IM服务商?
  • STM32(2)基础介绍及新建工程
  • Ton的编译过程(上)
  • Vue 文件转base64并获取文件编码格式
  • Spring 中使用的设计模式全面解析
  • flink 常见的缩减状态的方式
  • Java并发编程实战 03 | Java线程状态
  • python-pptx在PPT中插入各种形状
  • 【Hadoop|HDFS篇】NameNode和SecondaryNameNode
  • 设计模式学习[5]---装饰模式
  • sqlgun靶场漏洞挖掘
  • 安泰功率放大器有哪些特点呢
  • Linux从入门到开发实战(C/C++)Day13-线程池
  • 滚雪球学SpringCloud[1.1]:Spring Cloud概述与环境搭建(入门章节)
  • QT中使用UTF-8编码
  • Linux echo命令讲解及与重定向符搭配使用方法,tail命令及日志监听方式详解
  • 从戴尔公司中国大饭店DTF大会,看科技外企如何在中国市场发展
  • Docker快速部署Apache Guacamole
  • 前端三件套(HTML,CSS,JS)查漏补缺
  • 交换两实数的整数部分
  • 【数据结构】选择题错题集
  • log4j 的参数配置
  • CUDA-中值滤波算法
  • git标签、repo如何打tag