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

输出结果:
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()

输出结果:
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()

输出结果:
hamburger
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容