文章目录
Python函数装饰器笔记
函数装饰器也是一种函数,它的参数和返回值均为一个函数(但不是同一个)。通过其可以在不修改函数或方法定义的情况下动态地修改函数或类的行为。
def test_decorator(func):
def wrapper(*args, **kwargs):
print("函数开始执行")
result = func(*args, **kwargs) # 用于接收原函数的返回结果
print("函数结束执行")
return result
return wrapper
@test_decorator
def test_function(test):
print("函数执行中")
print(f"参数:{test}")
if __name__ == '__main__':
test_function("test")
输出:
函数开始执行
函数执行中
参数:test
函数结束执行
在上述代码中,@test_decorator
的作用等价于test_function = test_decorator(test_function)
。先把test_function函数作为参数传给test_decorator函数,test_decorator函数返回在其内部定义的wrapper函数使test_function("test")
调用的已经不是原来的test_function函数而是wrapper函数