探索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 是一个装饰器,它接受一个函数 func 并定义了一个内部函数 wrapperwrapper 函数在调用 func 之前和之后执行一些代码,有效地“装饰”了 func 的行为。使用 @my_decorator 语法将 say_hello 函数“装饰”起来,使其在调用前后打印额外的信息。

posted @ 2025-06-27 11:17  马瑞鑫03  阅读(11)  评论(0)    收藏  举报