1

我有一个f接受参数的函数iABi是计数器,A并且B是列表或常量。该函数只是添加第 i 个元素,A如果B它们是列表。这是我用 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)方法来实现我在上面所做的事情?

4

2 回答 2

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
于 2017-05-19T05:02:55.777 回答
0

你可以做:

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
于 2017-05-19T04:23:21.150 回答