我想创建一个“功能管道”,就像工厂一样。
假设我有以下功能:
def func1(var):
var = # do something with var
return var
def func2(var):
var = # do something else with var
return var
def func3(var):
var = # do another thing with var
return var
def func4(var):
var = # do something with var we haven't done before
return var
现在我想按顺序调用对象上的所有函数,但我想测试以所有可能的顺序排列调用它们并检查结果,因为最终结果将根据调用函数的顺序而变化。
如何更改此手动函数调用顺序:
myvar = something
myvar = func1(myvar)
myvar = func2(myvar)
myvar = func3(myvar)
myvar = func4(myvar) # final variable function transformation (result)
...我可以迭代所有可能的序列,但无需按如下方式手动编码?
def func1(var):
var = # do something with var
return var
def func2(var):
var = # do something else with var
return var
def func3(var):
var = # do another thing with var
return var
def func4(var):
var = # do something with var we haven't done before
return var
myvar = func4(func3(func2(func1(myvar))))
# or
myvar = func3(func4(func2(func1(myvar))))
# or
myvar = func3(func2(func4(func1(myvar))))
# or
myvar = func3(func2(func1(func4(myvar))))
# or
myvar = func4(func2(func3(func1(myvar))))
# or
# ...etc...
# or (finally)
myvar = func1(func2(func3(func4(myvar))))
要获取所有函数排列,您可以使用
itertools.permutations
还可以将一系列函数应用于一个值,您可以使用
functools.reduce
import functools
import reduce
def applyfunc(val, func):
return func(val)
def apply_sequence(sequence, val):
return functools.reduce(applyfunc, sequence, val)
def apply_permutations(func_list, val):
return map(apply_sequence,
itertools.permutations(sequence))
# use it like this:
for v in apply_permutations([f1, f2, f3, f4], val):
print v