美文网首页
Python装饰器

Python装饰器

作者: WZChan | 来源:发表于2017-11-27 14:51 被阅读0次
    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

    相关文章

      网友评论

          本文标题:Python装饰器

          本文链接:https://www.haomeiwen.com/subject/rvwzyxtx.html