码迷,mamicode.com
首页 > 其他好文 > 详细

装饰器

时间:2020-01-19 19:12:27      阅读:58      评论:0      收藏:0      [点我收藏+]

标签:跳过   def   装饰器   turn   code   div   return   结果   ali   

def makeBold(fun):
    print("***** 1 *******")
    def wrapped():
        print("------ 1 ------")
        return "<b> " + fun() + " <\\b>"
    return wrapped


def makeItalic(fun):
    print("***** 2 *******")
    def wrapped():
        print("------- 2 ------")
        return "<i> " + fun() + " <\i>"
    return wrapped


@makeBold
@makeItalic
def fun():
    return "hello world"


print(fun())

输出:

***** 2 *******
***** 1 *******
------ 1 ------
------- 2 ------
<b> <i> hello world <\i> <\b>

由此可见,解释器解释过程为:执行到@makeBold时,发现底下仍然是个装饰器,于是跳过先执行@makeItalic,等完成@makeItalic对fun的装饰(结果是返回一个函数),再返过去用@makeBold装饰第一步返回的函数

装饰器

标签:跳过   def   装饰器   turn   code   div   return   结果   ali   

原文地址:https://www.cnblogs.com/olivertian/p/12215135.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!