Python 函数链接次数未知

Python function chaining an unknown number of times

在 Python 中有没有办法在一个对象上将相同的函数链接到未知次数?

例如。如果我想将函数 fn 链接到对象 obj 两次,我会:

obj.fn(**kwargs1).fn(**kwargs2)

如果我想将 fn 链接五次,我会:

obj.fn(**kwargs1).fn(**kwargs2).fn(**kwargs3).fn(**kwargs4).fn(**kwargs5)

您实际上可以使用一个简单的 for 循环,它遍历参数列表,并将每个参数应用于对象,并将结果重新分配回对象

for args in list_of_args:

    obj = obj.fn(*args)

例如,我可以使用这个逻辑来链接 string.replace,如下所示

obj = 'aaaccc'
list_of_args = [['a','b'], ['c','d']]

for args in list_of_args:
    obj = obj.replace(*args)

print(obj)

输出将是

bbbddd

这与 'aaabbb'.replace('a','b').replace('c','d')

相同

或者我们也可以使用递归方法,它接受对象和一个计数器,它作为要应用的当前参数的索引,以及函数需要的次数 运行

#fn is either defined, or imported from outside
def chain_func(obj, counter, max_count):

    #If counter reaches max no of iterations, return
    if counter == max_count:
        return obj

    #Else recursively apply the function
    else:
        return chain_func(obj.fn(list_of_args[counter]), counter+1, max_count)

#To call it twice
list_of_args = [kwargs1, kwargs2]
chain_func(obj, 0, 2)

例如,我可以使用这个逻辑来链接 string.replace,如下所示

def chain_func(obj, counter, max_count):

    #If counter reaches max no of iterations, return
    if counter == max_count:
        return obj

    #Else recursively apply the function
    else:
        return chain_func(obj.replace(*list_of_args[counter]), counter+1, max_count)


list_of_args = [['a','b'], ['c','d']]
print(chain_func('aaaccc', 0, 2))

输出将是

bbbddd