【问题标题】:Decorator approach to function polymorphism in Python 3Python 3 中函数多态的装饰器方法
【发布时间】:2017-05-19 03:58:26
【问题描述】:

我有一个函数f 接受参数iABi 是一个计数器,AB 是列表或常量。该函数只是添加AB 的第i 个元素(如果它们是列表)。这是我用 Python 3 编写的。

def const_or_list(i, ls):
    if isinstance(ls, list):
        return ls[i]
    else:
        return ls

def f(i, A, B):
    _A = const_or_list(i, A)
    _B = const_or_list(i, B)
    return _A + _B

M = [1, 2, 3]
N = 11
P = [5, 6, 7]
print(f(1, M, N)) # gives 13
print(f(1, M, P)) # gives 8

您会注意到const_or_list() 函数在两个(但不是全部)输入参数上被调用。是否有一种装饰器(可能更 Pythonic)方法来实现我在上面所做的事情?

【问题讨论】:

标签: python python-decorators parametric-polymorphism


【解决方案1】:

我认为在这种情况下更多的 Pythonic 不是使用装饰器。我会摆脱 isinstance,改用 try/except 并摆脱中间变量:

代码:

def const_or_list(i, ls):
    try:
        return ls[i]
    except TypeError:
        return ls

def f(i, a, b):
    return const_or_list(i, a) + const_or_list(i, b)

测试代码:

M = [1, 2, 3]
N = 11
P = [5, 6, 7]
Q = (5, 6, 7)
print(f(1, M, N))  # gives 13
print(f(1, M, P))  # gives 8
print(f(1, M, Q))  # gives 8

结果:

13
8
8

但我真的需要一个装饰器:

很好,但它是很多更多代码......

def make_const_or_list(param_num):
    def decorator(function):
        def wrapper(*args, **kwargs):
            args = list(args)
            args[param_num] = const_or_list(args[0], args[param_num])
            return function(*args, **kwargs)
        return wrapper
    return decorator

@make_const_or_list(1)
@make_const_or_list(2)
def f(i, a, b):
    return a + b

【讨论】:

  • 感谢您的回复。关于 try and catch 异常方法的要点。实际上,装饰器方法在代码方面似乎更长。但它将最终功能简化为简单的单行。在我的实际用例中,公式要复杂得多且不断变化,清晰是最重要的。
【解决方案2】:

你可以这样做:

def const_or_list(i, ls):
    if isinstance(ls, list):
        return ls[i]
    else:
        return ls

def f(*args):
    i_ip = args[0]
    result_list = []
    for i in range(1, len(args)):
        result_list.append(const_or_list(i_ip, args[i]))
    return sum(result_list)

M = [1, 2, 3]
N = 11
P = [5, 6, 7]
print(f(1, M, N)) # gives 13
print(f(1, M, P)) # gives 8

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-17
    • 1970-01-01
    • 2011-09-18
    • 2012-02-09
    • 2020-07-13
    • 2011-03-23
    • 2015-02-21
    • 2016-07-04
    相关资源
    最近更新 更多