【Python知识】Python进阶-什么是装饰器?

Python装饰器介绍

    • 概述
      • [1. 基本装饰器](#1. 基本装饰器)
      • [2. 带参数的装饰器](#2. 带参数的装饰器)
      • [3. 带参数的函数装饰器(使用`functools.wraps`)](#3. 带参数的函数装饰器(使用functools.wraps))
      • [4. 类装饰器](#4. 类装饰器)
      • [5. 方法装饰器(在类中使用)](#5. 方法装饰器(在类中使用))
    • 参考文献

概述

Python装饰器是一种高级功能,允许你在不修改函数或方法定义的情况下,为其添加额外的功能或行为。装饰器本质上是一个高阶函数,它接受一个函数作为参数,并返回一个新的函数(或可调用对象)。下面是一些常见的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

@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.

2. 带参数的装饰器

装饰器也可以接受参数,这允许你创建更灵活的装饰器。

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

@repeat(num_times=3)
def greet(name):
    print(f"Hello, {name}!")

greet("Alice")

输出:

复制代码
Hello, Alice!
Hello, Alice!
Hello, Alice!

3. 带参数的函数装饰器(使用functools.wraps

为了保持被装饰函数的元数据(如函数名、文档字符串等),可以使用functools.wraps装饰器。

python 复制代码
import functools

def debug(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        print(f"{func.__name__}({args!r}, {kwargs!r}) = {result!r}")
        return result
    return wrapper

@debug
def add(a, b):
    return a + b

print(add(2, 3))

输出:

复制代码
add((2, 3), {}) = 5
5

4. 类装饰器

类装饰器与函数装饰器类似,但它们应用于类而不是函数。

python 复制代码
def singleton(cls):
    instances = {}
    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]
    return get_instance

@singleton
class MyClass:
    def __init__(self, value):
        self.value = value

obj1 = MyClass(10)
obj2 = MyClass(20)

print(obj1.value)  # 输出: 10
print(obj2.value)  # 输出: 10,因为obj1和obj2是同一个实例

5. 方法装饰器(在类中使用)

虽然方法本质上也是函数,但直接在类中为方法定义装饰器需要稍微不同的语法。

python 复制代码
def method_decorator(func):
    def wrapper(self, *args, **kwargs):
        print("Method is being called")
        return func(self, *args, **kwargs)
    return wrapper

class MyClass:
    @method_decorator
    def my_method(self):
        print("Inside my_method")

obj = MyClass()
obj.my_method()

输出:

复制代码
Method is being called
Inside my_method

请注意,对于类中的方法,装饰器通常还需要接受self(或cls对于类方法)作为第一个参数。

这些例子展示了装饰器在Python中的多种用途。装饰器是Python中一个非常强大且灵活的工具,可以用来实现各种设计模式、日志记录、性能测量、事务管理等功能。

参考文献

【Python知识】Python面向对象编程知识

相关推荐
mortimer1 小时前
安装NVIDIA Parakeet时,我遇到的两个Pip“小插曲”
python·github
@昵称不存在1 小时前
Flask input 和datalist结合
后端·python·flask
爱装代码的小瓶子1 小时前
数据结构之队列(C语言)
c语言·开发语言·数据结构
赵英英俊2 小时前
Python day25
python
东林牧之2 小时前
Django+celery异步:拿来即用,可移植性高
后端·python·django
何双新2 小时前
基于Tornado的WebSocket实时聊天系统:从零到一构建与解析
python·websocket·tornado
Maybe_ch3 小时前
.NET-键控服务依赖注入
开发语言·c#·.net
超浪的晨3 小时前
Java UDP 通信详解:从基础到实战,彻底掌握无连接网络编程
java·开发语言·后端·学习·个人开发
终焉暴龙王3 小时前
CTFHub web进阶 php Bypass disable_function通关攻略
开发语言·安全·web安全·php
AntBlack3 小时前
从小不学好 ,影刀 + ddddocr 实现图片验证码认证自动化
后端·python·计算机视觉