defwrapper(*args, **kwargs): print("Decorator A: Before function call") result = func(*args, **kwargs) print("Decorator A: After function call") return result
return wrapper
defdecorator_b(func): print('decorator b')
defwrapper(*args, **kwargs): print("Decorator B: Before function call") result = func(*args, **kwargs) print("Decorator B: After function call") return result
decorator b decorator_a Decorator A: Before function call Decorator B: Before function call Hello, Alice! Decorator B: After function call Decorator A: After function call
这个时候的结果就比较有趣了。来分析一下日志,装饰器 a 和 b 两个装饰器的确是按照之前提到的逻辑执行了,但是装饰器实际的逻辑却和我们预想的不一样。
defwrapper(*args, **kwargs): print("Decorator A: Before function call") result = func(*args, **kwargs) print("Decorator A: After function call") return result
defwrapper(*args, **kwargs): print("Decorator A: Before function call") result = func(*args, **kwargs) print("Decorator A: After function call") return result
return wrapper
defdecorator_test2(func): print('decorator_b')
defwrapper(*args, **kwargs): print("Decorator B: Before function call") result = func(*args, **kwargs) print("Decorator B: After function call") return result
decorator_b decorator_a Decorator A: Before function call Decorator B: Before function call Hello, Alice! Decorator B: After function call Decorator A: After function call ------------------------------ decorator_b decorator_a Decorator A: Before function call Decorator B: Before function call Hello, Alice2! Decorator B: After function call Decorator A: After function call