2010-11-25 226 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)