Why can't Python decorators be chained across definitions?

前端 未结 3 1853
没有蜡笔的小新
没有蜡笔的小新 2021-02-09 01:43

Why arn\'t the following two scripts equivalent?

(Taken from another question: Understanding Python Decorators)

def makebold(fn):
    def wrapped():
             


        
3条回答
  •  Happy的楠姐
    2021-02-09 02:00

    The problem with the second example is that

    @makebold
    def makeitalic(fn):
        def wrapped():
            return "" + fn() + ""
        return wrapped
    

    is trying to decorate makeitalic, the decorator, and not wrapped, the function it returns.

    You can do what I think you intend with something like this:

    def makeitalic(fn):
        @makebold
        def wrapped():
            return "" + fn() + ""
        return wrapped
    

    Here makeitalic uses makebold to decorate wrapped.

提交回复
热议问题