如何在函数内调用任意数量的函数?

How to call arbitrary amount of functions inside a function?

我想将指定数量的函数作为参数传递给最外层的函数。 在中间函数中,我想调用任意数量的函数。 所以中间函数是内部函数的一组。根据特定标准,可能会或可能不会调用功能组。

在下面的示例中,最外层的函数正好接受 2 个参数,但中间函数应接受任意数量的函数。

EG:

def al_func1():
    print('al 1')


def al_func2():
    print('al 2')


def ml_func1():
    print('ml 1')


def ml_func2():
    print('ml 2')


def function_to_connect(hostname: str, al, ml):
    print(f'Connecting to {hostname}')
    if 'al' in hostname:
        al
    elif 'ml' in hostname:
        ml


def call_al(*al_functs):
    al_functs


def call_ml(*ml_functs):
    ml_functs


function_to_connect('ipi-al', call_al(al_func1(), al_func2()), call_ml(
    ml_func1(), ml_func2()))

基本上可以,但是不管"if"语句的结果如何,函数总是执行,而且顺序不是我期望的。

输出为:

al 1
al 2
ml 1
ml 2
Connecting to ipi-al

谢谢!

欢迎来到 Stack Overflow!

你非常接近!你需要在这里学习的是

  • Lambda 函数
  • 传递函数而不调用它们
  • 如何迭代打包参数(* 符号)

我为你修改了代码,我想这就是你想要的

def al_func1():
    print('al 1')


def al_func2():
    print('al 2')


def ml_func1():
    print('ml 1')


def ml_func2():
    print('ml 2')


def function_to_connect(hostname: str, al, ml):
    """
    This is the description for the function.

    :param str hostname: This is decription for 'hostname'
    :param function al: This is description for 'al'
    :param function ml: This is description for 'ml'
    """
    print(f'Connecting to {hostname}')
    if 'al' in hostname:
        al()
    elif 'ml' in hostname:
        ml()


def call_al(*al_functs):
    for func in al_functs:
        func()


def call_ml(*ml_functs):
    for func in ml_functs:
        func()


function_to_connect('ipi-al', lambda: call_al(al_func1, al_func2), lambda: call_ml(ml_func1, ml_func2))

当你传入函数时,你把“()”放在那里,它调用函数。

如何解决这个问题:

  • 删除输入末尾的“()”,这运行是函数
  • 在函数末尾添加“()”,这将实际调用函数并且运行它