def makebold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
def makeitalic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
@makeitalic
@makebold
def hello():
return "hello world"
print(hello()) ## returns "<b><i>hello world</i></b>"
在这段代码中,为什么不只定义函数makeitalic()和makebold()并传入函数hello?
我是否在这里错过了一些东西,或者装饰师在处理更复杂的事情上真的更好吗?
在这段代码中,为什么不只定义函数makeitalic()和makebold()并传入函数hello?
你当然可以!装饰器只是语法糖。实际情况是:
@makeitalic
@makebold
def hello():
return "hello world"
变成:
def hello():
return "hello world"
hello = makebold(hello)
hello = makeitalic(hello)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句