Advertisement
lessientelrunya

Function with args, kwargs

Apr 6th, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.77 KB | None | 0 0
  1. def a_decorator_passing_arbitrary_arguments(function_to_decorate):
  2.     # The wrapper accepts any arguments
  3.     def a_wrapper_accepting_arbitrary_arguments(*args, **kwargs):
  4.         print("Do I have args?:")
  5.         print(args)
  6.         print(kwargs)
  7.         # Then you unpack the arguments, here *args, **kwargs
  8.         # If you are not familiar with unpacking, check:
  9.         # http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
  10.         function_to_decorate(*args, **kwargs)
  11.     return a_wrapper_accepting_arbitrary_arguments
  12.  
  13. @a_decorator_passing_arbitrary_arguments
  14. def function_with_no_argument():
  15.     print("Python is cool, no argument here.")
  16.  
  17. function_with_no_argument()
  18. #outputs
  19. #Do I have args?:
  20. #()
  21. #{}
  22. #Python is cool, no argument here.
  23.  
  24. @a_decorator_passing_arbitrary_arguments
  25. def function_with_arguments(a, b, c):
  26.     print(a, b, c)
  27.  
  28. function_with_arguments(1,2,3)
  29. #outputs
  30. #Do I have args?:
  31. #(1, 2, 3)
  32. #{}
  33. #1 2 3
  34.  
  35. @a_decorator_passing_arbitrary_arguments
  36. def function_with_named_arguments(a, b, c, platypus="Why not ?"):
  37.     print("Do {0}, {1} and {2} like platypus? {3}".format(a, b, c, platypus))
  38.  
  39. function_with_named_arguments("Belle", "Beast", "Lumiere", platypus="Indeed!")
  40. #outputs
  41. #Do I have args ? :
  42. #('Belle', 'Beast', 'Lumiere')
  43. #{'platypus': 'Indeed!'}
  44. #Do Belle, Beast and Lumiere like platypus? Indeed!
  45.  
  46. class MrsPotts(object):
  47.  
  48.     def __init__(self):
  49.         self.age = 31
  50.  
  51.     @a_decorator_passing_arbitrary_arguments
  52.     def sayYourAge(self, lie=-3): # You can now add a default value
  53.         print("I am {0}, what did you think?".format(self.age + lie))
  54.  
  55. m = MrsPotts()
  56. m.sayYourAge()
  57. #outputs
  58. # Do I have args?:
  59. #(<__main__.MrsPotts object at 0xb7d303ac>,)
  60. #{}
  61. #I am 28, what did you think?
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement