伟大的Python装饰器示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了伟大的Python装饰器示例相关的知识,希望对你有一定的参考价值。

  1. def decorator_maker_with_arguments(decorator_arg1, decorator_arg2) :
  2.  
  3. print "I make decorators ! And I accept arguments:", decorator_arg1, decorator_arg2
  4.  
  5. def my_decorator(func) :
  6. # The hability to pass arguments here is a gift from closures.
  7. # If you are not confortable with closures, you can assume it's ok,
  8. # or read : http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python
  9. print "I am the decorator. Somehow you passed me arguments:", decorator_arg1, decorator_arg2
  10.  
  11. # Don't confuse decorator arguments and function arguments !
  12. def wrapped(function_arg1, function_arg2) :
  13. print "I am the wrapper arround the decorated function.",
  14. " I can access all the variables",
  15. " - from the decorator:", decorator_arg1, decorator_arg2,
  16. " - from the function call:", function_arg1, function_arg2,
  17. " Then I can pass them to the decorated function"
  18. return func(function_arg1, function_arg2)
  19.  
  20. return wrapped
  21.  
  22. return my_decorator
  23.  
  24. @decorator_maker_with_arguments("Leonard", "Sheldon")
  25. def decorated_function_with_arguments(function_arg1, function_arg2) :
  26. print "I am the decorated function and only knows about my arguments :",
  27. function_arg1, function_arg2
  28.  
  29. decorated_function_with_arguments("Rajesh", "Howard")
  30. #outputs:
  31. #I make decorators ! And I accept arguments: Leonard Sheldon
  32. #I am the decorator. Somehow you passed me arguments: Leonard Sheldon
  33. #I am the wrapper arround the decorated function.
  34. #I can access all the variables
  35. # - from the decorator: Leonard Sheldon
  36. # - from the function call: Rajesh Howard
  37. #Then I can pass them to the decorated function
  38. #I am the decorated function and only knows about my arguments : Rajesh Howard

以上是关于伟大的Python装饰器示例的主要内容,如果未能解决你的问题,请参考以下文章

Python-装饰器-示例

Python进阶装饰器(Decorator)

Python 装饰器简单示例

Python 参数化装饰器

Python 装饰器示例

python学习笔记之装饰器(语法糖)