def my_shiny_new_decorator(a_function_to_decorate):
def the_wrapper_around_the_original_function():
print 'Befor the function runs'
a_function_to_decorate()
print 'After the function runs'
return the_wrapper_around_the_original_function
def a_stand_alone_function():
print "I'm a stand alone function, don't you dare modify me"
a_stand_alone_function()
a_stand_alone_function = my_shiny_new_decorator(a_stand_alone_function)
a_stand_alone_function()
@my_shiny_new_decorator
def another_stand_alone_function():
print 'Leave me alone'
another_stand_alone_function()
輸出結(jié)果:
def bread(func):
def wrapper():
print "</''''''\>"
func()
print "</______\>"
return wrapper
def ingredients(func):
def wrapper():
print "#tomatoes#"
func()
print "~salad~"
return wrapper
def sandwich(food="--ham--"):
print food
sandwich = bread(ingredients(sandwich))
sandwich()
輸出結(jié)果:
def bread(func):
def wrapper():
print "</''''''\>"
func()
print "</______\>"
return wrapper
def ingredients(func):
def wrapper():
print "#tomatoes#"
func()
print "~salad~"
return wrapper
@bread
@ingredients
def sandwich(food='--ham--'):
print food
sandwich()
輸出結(jié)果: