gpt4 book ai didi

Python装饰器与传递函数

转载 作者:太空狗 更新时间:2023-10-29 18:06:26 26 4
gpt4 key购买 nike

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 呢?

我是不是遗漏了什么,或者装饰器真的更适合处理更复杂的事情吗?

最佳答案

In this code, why not just define the functions makeitalic() and makebold() and pass in the function hello?

当然可以!装饰器只是语法糖。在引擎盖下,发生的是:

@makeitalic
@makebold
def hello():
return "hello world"

变成:

def hello():
return "hello world"

hello = makebold(hello)
hello = makeitalic(hello)

关于Python装饰器与传递函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43380329/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com