装饰器是Python中一个常用的高级特性,它可以用于修改或增强现有函数的功能,而不需要修改函数的源代码。
简单来说,装饰器就是一个函数,它接收一个函数作为参数,并返回一个新的函数。新的函数可以在不改变原函数代码的情况下,增加一些额外的功能。
使用装饰器可以实现以下几个方面的功能:
使用装饰器的基本语法如下:
python @decorator def func(): pass
其中,@decorator就是装饰器,它可以是Python内置的装饰器,也可以是自定义的装饰器函数。func就是需要被装饰的函数。
一个简单的装饰器示例:
python def my_decorator(func): def wrapper(): print("Before the function is called.") func() print("After the function is called.") return wrapper @my_decorator def say_hello(): print("Hello!") say_hello()
运行结果为:
Before the function is called. Hello! After the function is called.
在这个例子中,my_decorator是一个装饰器函数,它接收一个函数作为参数,并返回一个新的函数wrapper。wrapper函数在调用原函数之前和之后,分别输出Before the function is called.和After the function is called.。通过@my_decorator的方式,将say_hello函数传递给my_decorator函数进行装饰,最终调用say_hello函数时,实际上调用的是wrapper函数。