伟大的Python装饰器示例
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了伟大的Python装饰器示例相关的知识,希望对你有一定的参考价值。
def decorator_maker_with_arguments(decorator_arg1, decorator_arg2) : print "I make decorators ! And I accept arguments:", decorator_arg1, decorator_arg2 def my_decorator(func) : # The hability to pass arguments here is a gift from closures. # If you are not confortable with closures, you can assume it's ok, # or read : http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python print "I am the decorator. Somehow you passed me arguments:", decorator_arg1, decorator_arg2 # Don't confuse decorator arguments and function arguments ! def wrapped(function_arg1, function_arg2) : print "I am the wrapper arround the decorated function.", " I can access all the variables", " - from the decorator:", decorator_arg1, decorator_arg2, " - from the function call:", function_arg1, function_arg2, " Then I can pass them to the decorated function" return func(function_arg1, function_arg2) return wrapped return my_decorator @decorator_maker_with_arguments("Leonard", "Sheldon") def decorated_function_with_arguments(function_arg1, function_arg2) : print "I am the decorated function and only knows about my arguments :", function_arg1, function_arg2 decorated_function_with_arguments("Rajesh", "Howard") #outputs: #I make decorators ! And I accept arguments: Leonard Sheldon #I am the decorator. Somehow you passed me arguments: Leonard Sheldon #I am the wrapper arround the decorated function. #I can access all the variables # - from the decorator: Leonard Sheldon # - from the function call: Rajesh Howard #Then I can pass them to the decorated function #I am the decorated function and only knows about my arguments : Rajesh Howard
以上是关于伟大的Python装饰器示例的主要内容,如果未能解决你的问题,请参考以下文章