# 定义一个测试函数 deftest_a(): print("This is a") return # 该测试函数赋值给a这个变量,再赋值给b这个变量 a = test_a b = a # 删除a这个变量,此时再运行a(),程序会出错, 但是b()仍然可以调用 del a b() # 删除 test_a() 这个函数, 再调用test_a() 时,程序会报错 del test_a # 此时b()仍然可以调用 b() # 会报错哦 test_a()
defa_new_decoarter(func): defwrapTheFuntion(): print("I'm doing som boring works before running my function") func() print("After") return wrapTheFuntion defa(): print("Funciton A is Running") a = a_new_decoarter(a) a()
有了我们之前的经验,我们可以自然而然的得出,在我们运行到a()时,我们最终会输出三行字符串, 为:
1 2 3
I'm doing som boring works before running my function Funciton A is Running After
defa_new_decoarter(func): defwrapTheFuntion(): print("I'm doing som boring works before running my function") func() print("After") return wrapTheFuntion
@a_new_decoarter defb(): print("Function B is Running") # 这里使用了b()这个函数,来和上面的代码进行区别 b()
最终的运行结果如下:
1 2 3
I'm doing som boring works before running my function Function B is Running After
# 则可以使用如下的代码 from functools import wraps defa_new_decorator(a_func): # 利用wraps 先包装a_func 函数,再利用 decorater 函数进行包装 @wraps(a_func) # 剩下的函数逻辑都是一样的 defwrapTheFunction(): print("I am doing some boring work before executing a_func()") a_func() print("I am doing some boring work after executing a_func()") return wrapTheFunction @a_new_decorator defa_function_requiring_decoration(): print("I am the function which needs some decoration to " "remove my foul smell") a_function_requiring_decoration() print(a_function_requiring_decoration.__name__) # Output: a_function_requiring_decoration