Advertisement
Guest User

Decorator vs Wrapper

a guest
Dec 10th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.96 KB | None | 0 0
  1. def add1_decorator(func):
  2.     """
  3.    a decorator
  4.    it adds 1 to the result and prints "I'm decorated"
  5.    """
  6.     def inner(*args, **kwargs):
  7.         print("I'm decorated")
  8.         return func(*args, **kwargs) + 1
  9.     return inner
  10.  
  11. def add2_wrapper(fun, *args, **kwargs):
  12.     """
  13.    a wrapper
  14.    a function that takes another function as argument
  15.    it adds 2 to the result of the function and prints "I'm wrapped"
  16.    """
  17.     print ("I'm wrapped")
  18.     return fun(*args, **kwargs) + 2
  19.  
  20.  
  21. def sum_base(a,b):
  22.     """
  23.    a base function
  24.    """
  25.     return a+b
  26.  
  27. @add1_decorator
  28. def sum_decorated(a,b):
  29.     """
  30.    a decorated function
  31.    """
  32.     return a+b
  33.  
  34. def sum_wrapped(func, a, b):
  35.     """
  36.    a wrapped function
  37.    """
  38.     return add2_wrapper(sum_base, a, b)
  39.  
  40. print('Base function:')
  41. print(sum_base(2, 3))
  42. print('Decorated function:')
  43. print(sum_decorated(2, 3))
  44. print('Wrapped function:')
  45. print(sum_wrapped(sum_base, 2, 3))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement