Advertisement
Guest User

Untitled

a guest
Mar 31st, 2020
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.78 KB | None | 0 0
  1.  
  2. # ============== 方案1 ======================
  3. def non_decorator(func):
  4.     run_something_before()
  5.     result = func()
  6.     run_something_after()
  7.     return result
  8.  
  9.  
  10. def func1():
  11.     print(123)
  12.  
  13.  
  14. def func2():
  15.     print(456)
  16.  
  17.  
  18. # 我需要在func1和func2执行前后都做一些处理
  19. # 所以用定义的“非装饰器函数”来包装一下,变成这样执行
  20.  
  21. non_decorator(func1)
  22. non_decorator(func2)
  23.  
  24.  
  25. # ================ 方案2 ======================
  26. def real_decorator(func):
  27.     def wrapper():
  28.         run_something_before()
  29.         result = func()
  30.         run_something_after()
  31.         return result
  32.     return wrapper
  33.  
  34. @real_decorator
  35. def func1():
  36.     print(123)
  37.  
  38.  
  39. @real_decorator
  40. def func2():
  41.     print(456)
  42.  
  43. # 执行
  44. func1()
  45.  
  46. func2()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement