用Python语法调用函数
嘿,我正在用python 2.6编写一个小程序,我已经定义了 2个助手函数,几乎可以实现我想要的所有功能,例如用Python语法调用函数,python,syntax,Python,Syntax,嘿,我正在用python 2.6编写一个小程序,我已经定义了 2个助手函数,几乎可以实现我想要的所有功能,例如 def helper1: ... def helper2: ... 现在我的问题是,我想创建一个新函数,将两个函数合并到一个函数中,这样我就不必在shell中编写: list(helper1(helper2(argument1,argument2))) 而是 function(argument1,argument2) 有没有捷径可走?我是python新手,还是
def helper1:
...
def helper2:
...
现在我的问题是,我想创建一个新函数,将两个函数合并到一个函数中,这样我就不必在shell中编写:
list(helper1(helper2(argument1,argument2)))
而是
function(argument1,argument2)
有没有捷径可走?我是python新手,还是需要更多的代码示例才能回答
如需任何提示或帮助,请提前联系Thanx
def function(arg1, arg2):
return list(helper1(helper2(arg1, arg2)))
应该有用
function = lambda x, y: list(helper1(helper2(x, y)))
这是高阶函数compose的一个例子。躺在那里很方便
function = lambda x, y: list(helper1(helper2(x, y)))
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)
等等。这是高阶函数组合的一个示例。躺在那里很方便
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)
等等