3

我设法编写了一个带有参数的装饰器,但我对两个实际的装饰器具有相同的代码行这一事实感到困扰:

def wrapper(*args, **kwargs):
    r = fn(*args)

并且想知道是否有某种方法可以解决这种违反 DRY 的问题

def fix(double):
    def outer(fn):
        if double:
            def wrapper(*args, **kwargs):
                r = fn(*args)
                return 2 * r
            return wrapper
        else:
            def wrapper(*args, **kwargs):
                r = fn(*args)
                return r
            return wrapper
    return outer
4

2 回答 2

2

另一种可能是

def fix(double):
    def outer(fn):
        def wrapper(*args, **kwargs):
            r = fn(*args, **kwargs) # do that right!
            return 2 * r if double else r
        return wrapper
    return outer

甚至 - 因为如果double是- 你不会改变任何东西False- :

def fix(double):
    def outer(fn):
        if not double: return fn
        def wrapper(*args, **kwargs):
            r = fn(*args, **kwargs) # do that right!
            return 2 * r
        return wrapper
    return outer
于 2012-08-01T17:07:59.903 回答
2

如果 double 为 False,您可以乘以 1:

def fix(double):
    def outer(fn):
        factor = 2 if double else 1
        def wrapper(*args, **kwargs):
            r = fn(*args)
            return factor * r
        return wrapper
    return outer
于 2012-08-01T16:28:09.197 回答