编写python闭包的更好方法是什么?

时间:2013-05-28 21:32:53

标签: python closures

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

  • 是的,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>

1 个答案:

答案 0 :(得分: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)