Python装饰器vs传递函数
问题描述:
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?Python装饰器vs传递函数
我在这里错过了什么,或者是装饰者真的更适合更复杂的事情吗?
答
在这段代码中,为什么不直接定义函数makeitalic()和makebold()并传入函数hello?
你当然可以!装饰者只是语法糖。引擎盖下,会发生什么情况是:
@makeitalic
@makebold
def hello():
return "hello world"
变为:
def hello():
return "hello world"
hello = makebold(hello)
hello = makeitalic(hello)
感谢,似乎没有必要在这种情况下。我相信他们在其他使用案例中提供简洁。 –