簡體   English   中英

Python function 接受兩個函數並返回串聯的 function?

[英]Python function that takes two functions and returns the concatenated function?

I need to write a python function called 'concat' that takes any two functions as input, and returns a function, which is the concatenated function of the two input functions (ie it takes f1 and f2, and returns f1◦f2).

我試過這個:

def concat(f1,f2):
    return f1(f2)

例如,如果 f1 和 f2 是:

def f1(x):
    return x+2
def f2(x):
    return x*2

那么, concat(f1,f2) 應該返回: (x*2)+2

我希望能夠像這樣使用它:

a = concat(f1,f2)
a(5)

但我收到一個錯誤:

類型錯誤:+ 不支持的操作數類型:'function' 和 'int'

我知道我可以像這樣定義 function:

def concat(f1,f2,x): 
    return f1(f2(x))

但這不是我想要的; 我希望能夠創建 concat function 的實例,然后可以使用任何 x 調用它。

您需要返回一個新的“包裝器”function。 一種選擇是使用lambda表達式:

def concat(f1, f2):
    return lambda x: f1(f2(x))

文檔 https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions

我認為你想要的是一個closure

def concat(f1, f2):
  def f3(x):
    return f1(f2(x))
  return f3

Python 中的函數被認為是第一個 class 對象。 這允許它們像普通變量一樣被創建和操作。 在這種情況下, concat正在構造一個新的 function ,它包含兩個函數。

這里使用的第二個屬性是詞法作用域。 新的 function 保留了對局部變量的訪問權,它是在定義的地方而不是執行的地方。 這允許返回的 function 在任何地方運行,而不會失去對復合函數的訪問權限。

這是組合兩個以上函數的可能解決方案。 使用閉包循環函數並使用前一個函數的結果作為下一個函數的參數:

def compose(*fns):
    def F(x):
        for fn in fns[::-1]:
            x = fn(x)
        return x
    return F

然后定義你的組合並調用:

>>> F = compose(f1, f2, lambda x: x+1)
>>> F(4)
12 # f1(f2(f3(x)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM