Python装饰器

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()

输出结果:
Python装饰器_第1张图片
leave me alone
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()

输出结果:
Python装饰器_第2张图片
Hamburg
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()

输出结果:
Python装饰器_第3张图片
hamburger

你可能感兴趣的:(Python装饰器)