python

Python里的function如何实现装饰器

小樊
81
2024-09-29 14:52:04
栏目: 编程语言

在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 之前和之后分别执行了一些额外的操作。最后,my_decorator 返回了 wrapper 函数。

要使用装饰器,我们可以在要装饰的函数定义之前加上一个 @decorator_name 行。在这个例子中,我们在 say_hello 函数定义之前加上了 @my_decorator,这意味着当我们调用 say_hello 时,实际上是在调用 my_decorator(say_hello)

运行上面的代码,输出将会是:

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

这样,我们就成功地使用装饰器修改了 say_hello 函数的行为。

0
看了该问题的人还看了