1.背景
背景:我为啥单独写一片这个文章呢?是因为遇到好多次了 我必须搞懂它! 文章分三部分 1.1不带参数的多个装饰器 1.2带参数的装饰器 1.3带参数的实例,直接拿来用
2不带参数的多个装饰器‘
# 编写装饰器,作为响应以及请求的校验 def request_wrapper(fun): print(f"request_wrapper 1") def wrapper(*args, **kwargs): print(f"request_wrapper 2") fun(*args, **kwargs) print(f"request_wrapper 3") return wrapper def response_wrapper(fun): print(f"response_wrapper 1") def wrapper(*args, **kwargs): print(f"response_wrapper 2") fun(*args, **kwargs) print(f"response_wrapper 3") return wrapper @request_wrapper @response_wrapper def fun(): print(f"我是主程序") if __name__ == '__main__': fun()
3.带参数的多个装饰器
# 编写装饰器,作为响应以及请求的校验 def request_wrapper(xxxxxxxxxxxx): print(f"request_wrapper 1") def wrapper(fun): print(f"request_wrapper 2") def inner(*args, **kwargs): print(f"request_wrapper 3") fun(*args, **kwargs) print(f"request_wrapper 4") return inner print(f"request_wrapper 5") return wrapper def response_wrapper(xxxxxxxxxxxx): print(f"response_wrapper 1") def wrapper(fun): print(f"response_wrapper 2") def inner(*args, **kwargs): print(f"response_wrapper 3") fun(*args, **kwargs) print(f"response_wrapper 4") return inner print(f"response_wrapper 5") return wrapper @request_wrapper(111111) @response_wrapper(111111) def fun(): print(f"我是主程序") if __name__ == '__main__': fun()