# 定义一个装饰器 defmy_shiny_new_decorator(a_function_to_decorate): defthe_wrapper_around_the_original_function(): print("Before the function runs") a_function_to_decorate() print("After the function runs") return the_wrapper_around_the_original_function
# 定义一个普通函数 defa_stand_alone_function(): print("I am a stand alone function, don't you dare modify me")
defdecorator_maker_with_arguments(decorator_arg1, decorator_arg2): print("I make decorators! And I accept arguments: {0}, {1}".format(decorator_arg1, decorator_arg2)) defmy_decorator(func): print("I am the decorator. Somehow you passed me arguments: {0}, {1}".format(decorator_arg1, decorator_arg2)) defwrapped(function_arg1, function_arg2): print("I am the wrapper around the decorated function.\n" "I can access all the variables\n" "\t- from the decorator: {0} {1}\n" "\t- from the function call: {2} {3}\n" "Then I can pass them to the decorated function" .format(decorator_arg1, decorator_arg2, function_arg1, function_arg2)) return func(function_arg1, function_arg2) return wrapped return my_decorator
@decorator_maker_with_arguments("Leonard", "Sheldon") defdecorated_function_with_arguments(function_arg1, function_arg2): print("I am the decorated function and only knows about my arguments: {0} {1}".format(function_arg1, function_arg2))