-6

我的问题可以用简单的是或否来回答:

  • italic的,“闭包风格”是编写 python 闭包的更好方法——换句话说—— italic“闭包表示法”不会破坏并且没有警告

  • 不,italic的闭包是有问题的,bold' 的“闭包符号”是唯一的出路

以防万一,如果有人想知道“怎么了”,错了为什么“他”不使用标准闭包——标准形式,这让我想逃跑。

def example():

    # The standard X_x closure...
    #
    def bold(predecessor):
        def successor():
            return "<bold/>" + predecessor() + "</bold>"
        return successor

    # ...this looks sooo much better ^.^
    #
    def italic(predecessor):
        x = predecessor
        def successor():
            return "<italic/>" + x() + "</italic>"
        return successor

    def underline(predecessor):
        x = predecessor
        def successor():
            return "<underline/>" + x() + "</underline>"
        return successor

    @italic
    @bold
    @underline
    def trademark():
        return "This trademark cant be changed."

    print(trademark())
    #example() prints <italic/><bold/><underline/>This trademark cant be changed.</underline></bold</italic>
4

1 回答 1

8

当然,你可以这样做:

def italic(predecessor):
    x = predecessor
    def successor():
        return "<italic/>" + x() + "</italic>"
    return successor

就像你可以这样做:

def italic(predecessor):
    x = predecessor
    x2 = x
    def successor():
        return "<italic/>" + x2() + "</italic>"
    return successor

或者

def italic(predecessor):
    x = predecessor
    x2 = x
    x3 = x2
    def successor():
        return "<italic/>" + x3() + "</italic>"
    return successor

但你为什么想要?


编写装饰器的最好方法是functools.wraps

from functools import wraps

def italic(f):
    @wraps(f)
    def decorated():
        return "<italic/>" + f() + "</italic>"
    return decorated

但如果你真的想与众不同:

import functools

def italic(f):
    return functools.update_wrapper(lambda: "<italic/>" + f() + "</italic>", f)
于 2013-05-28T21:36:48.163 回答