Python 将多个函数合二为一

Python chain several functions into one

我有几个字符串处理函数,例如:

def func1(s):
    return re.sub(r'\s', "", s)

def func2(s):
    return f"[{s}]"
...

我想将它们组合成一个管道函数:my_pipeline(),这样我就可以将它用作参数,例如:

class Record:
    def __init__(self, s):
        self.name = s
    
    def apply_func(self, func):
        return func(self.name)

rec = Record(" hell o")
output = rec.apply_func(my_pipeline)
# output = "[hello]"

目标是使用my_pipeline作为参数,否则我需要一个一个调用这些函数。

谢谢。

您可以只创建一个调用这些函数的函数:

def my_pipeline(s):
    return func1(func2(s))

您可以编写一个简单的工厂函数或class构建一个管道函数:

>>> def pipeline(*functions):
...     def _pipeline(arg):
...         restult = arg
...         for func in functions:
...             restult = func(restult)
...         return restult
...     return _pipeline
...
>>> rec = Record(" hell o")
>>> rec.apply_func(pipeline(func1, func2))
'[hello]'

使用函数列表(因此您可以 assemble 这些其他地方):

def func1(s):
    return re.sub(r'\s', "", s)

def func2(s):
    return f"[{s}]"

def func3(s):
    return s + 'tada '

def callfuncs(s, pipeline):
    f0 = s
    pipeline.reverse()
    for f in pipeline:
        f0 = f(f0)        
    return f0

class Record:
    def __init__(self, s):
        self.name = s

    def apply_func(self, pipeline):
        return callfuncs(s.name, pipeline)
        
# calling order func1(func2(func3(s)))
my_pipeline = [func1, func2, func3]
rec = Record(" hell o")
output = rec.apply_func(my_pipeline)