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()
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
作为参数。wrapper
是一个内部函数,它在调用func
之前和之后分别打印一些信息。my_decorator
返回wrapper
函数。@my_decorator
是 Python 的装饰器语法糖,它等价于say_hello = my_decorator(say_hello)
。- 当我们调用
say_hello()
时,实际上调用的是wrapper
函数,它会在调用say_hello
之前和之后打印信息。
输出结果:
Something is happening before the function is called. Hello! Something is happening after the function is called.
点我分享笔记