Python 装饰器进阶

装饰器是 Python 中一种非常强大的功能,它允许程序员在不修改原有函数的情况下,给函数增加额外的功能。本文将深入探讨 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.

带参数的装饰器

装饰器也可以带参数。以下是如何创建一个带参数的装饰器的例子:

def decorator_with_args(number):
    def my_decorator(func):
        def wrapper(*args, **kwargs):
            print("Decorator received the number: {}".format(number))
            return func(*args, **kwargs)
        return wrapper
    return my_decorator

@decorator_with_args(42)
def say_hello(name):
    print("Hello, {}!".format(name))

say_hello("Alice")

输出结果如下:

Decorator received the number: 42
Hello, Alice!

类装饰器

装饰器也可以是类。以下是一个使用类装饰器的例子:

class MyDecorator(object):
    def __init__(self, func):
        self.func = func

    def __call__(self):
        print("Something is happening before the function is called.")
        self.func()
        print("Something is happening after the function is called.")

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

say_hello()

输出结果如下:

Something is happening before the function is called.
Hello!
Something is happening after the function is called.

扩展阅读

如果您想了解更多关于 Python 装饰器的信息,可以阅读Python 装饰器官方文档

希望这篇文章能帮助您更好地理解 Python 装饰器的进阶用法。😊