装饰器是 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()

在上面的例子中,my_decorator 是一个装饰器,它接收 say_hello 函数作为参数,并返回一个新的函数 wrapper。当调用 say_hello() 时,实际上是在调用 wrapper()

装饰器参数

装饰器可以接受参数,这使得它们更加灵活。

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_with_args 接收一个参数 number,并将其传递给装饰器内部函数 my_decorator

类装饰器

装饰器不仅可以应用于函数,还可以应用于类。

def class_decorator(cls):
    class NewClass(cls):
        def __init__(self, *args, **kwargs):
            print("Something is happening before the instance is created!")
            super().__init__(*args, **kwargs)
        def do_something(self):
            print("Something is happening inside the instance!")
    return NewClass

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

my_instance = MyClass(10)
my_instance.do_something()

在这个例子中,class_decorator 是一个装饰器,它接收一个类 cls 作为参数,并返回一个新的类 NewClass

总结

装饰器是 Python 中一种非常强大的功能,它可以帮助你以简洁的方式添加额外的功能。通过理解装饰器的原理和应用,你可以写出更加灵活和可扩展的代码。

更多关于 Python 装饰器的信息

[center]decorator