是否有一种方法将Python元组扩展为函数-作为实际的参数?
例如,expand()在这里发挥了作用:
some_tuple = (1, "foo", "bar")
def myfun(number, str1, str2):
return (number * 2, str1 + str2, str2 + str1)
myfun(expand(some_tuple)) # (2, "foobar", "barfoo")
我知道可以将myfun定义为myfun((a, b, c)),但当然可能存在遗留代码。
谢谢
类似于@Dominykas的回答,这是一个将接受多参数函数转换为接受元函数的装饰器:
apply_tuple = lambda f: lambda args: f(*args)
示例1:
def add(a, b):
return a + b
three = apply_tuple(add)((1, 2))
示例2:
@apply_tuple
def add(a, b):
return a + b
three = add((1, 2))
类似于@Dominykas的回答,这是一个将接受多参数函数转换为接受元函数的装饰器:
apply_tuple = lambda f: lambda args: f(*args)
示例1:
def add(a, b):
return a + b
three = apply_tuple(add)((1, 2))
示例2:
@apply_tuple
def add(a, b):
return a + b
three = add((1, 2))