gpt4 book ai didi

python - Python 3 中函数多态性的装饰器方法

转载 作者:太空宇宙 更新时间:2023-11-03 15:13:22 25 4
gpt4 key购买 nike

我有一个函数 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风格不是使用装饰器。我将摆脱 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

关于python - Python 3 中函数多态性的装饰器方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44061206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com