在函数中调用2个函数

Jim*_*Jim 3 python function python-3.x

问题如下:

写一个函数撰写这需要两个函数作为参数,我们称他们为FaFb,并返回一个函数,Fres,这意味着从其它功能outdata是INDATA到第一,例如:Fres(x) = Fa(Fb(x)).运行示例:

>>> def multiply_five(n):
... return n * 5
...
>>> def add_ten(x):
... return x + 10
...
>>> composition = compose(multiply_five, add_ten)
>>> composition(3)
65
>>> another_composition = compose(add_ten, multiply_five)
>>> another_composition(3)
25
Run Code Online (Sandbox Code Playgroud)

所以我理解这一点,如果我发送3函数compose将需要3 + 10 = 13之后将结果发送到乘法函数它会做:13*5女巫是65.这是我到目前为止写的代码:

def multiply_five(n):
    return n*5

def add_ten(x):
    return x+10

def compose(func1, func2):
    def comp(arg):
        return func2(arg)
    return func1(comp(arg))
Run Code Online (Sandbox Code Playgroud)

我得到编译错误,我尝试了一些不同的方法:

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    composition = compose(multiply_five, add_ten)
  File "C:\Users\Jim\Desktop\tdp002\5h.py", line 10, in compose
    return func1(comp(arg))
NameError: name 'arg' is not defined
Run Code Online (Sandbox Code Playgroud)

che*_*ner 7

你不想打电话要么func1func2尚未; 你只想返回一个可以同时调用它们的函数.

def compose(func1, func2):
    def _(*args, **kw):
        return func1(func2(*args, **kw))
    return _
Run Code Online (Sandbox Code Playgroud)

您也可以使用lambda表达式来创建组合函数.

def compose(func1, func2):
    return lambda *args, **kw: func1(func2(*args, **kw))
Run Code Online (Sandbox Code Playgroud)