2010-11-25 221 views
1

嘿即时在Python 2.6编写的小程序,我已经定义 2的辅助功能,这确实几乎所有我想要的,例如呼叫Python语法功能

def helper1: 
    ... 


def helper2: 
    ... 

现在我的问题是,我想使一个新的功能集两种功能于一体的功能,所以我没有写(壳):

list(helper1(helper2(argument1,argument2))) 

而只是

function(argument1,argument2) 

有没有什么简单的方法呢?我是新来的Python,还是你需要更多的代码示例才能够回答?

感谢名单提前任何提示或帮助

回答

8
def function(arg1, arg2): 
    return list(helper1(helper2(arg1, arg2))) 

应该工作。

2
function = lambda x, y: list(helper1(helper2(x, y))) 
2

这是高阶函数compose的一个例子。这是方便有周围铺设

def compose(*functions): 
    """ Returns the composition of functions""" 
    functions = reversed(functions) 
    def composition(*args, **kwargs): 
     func_iter = iter(functions) 
     ret = next(func_iter)(*args, **kwargs) 
     for f in func_iter: 
      ret = f(ret) 
     return ret 
    return composition 

现在你可以写你的功能

function1 = compose(list, helper1, helper2) 
function2 = compose(tuple, helper3, helper4) 
function42 = compose(set, helper4, helper2)