将 Python 函数作为参数传递而不执行它?

Dan*_*Von 3 python function keyword-argument

我有这个功能:

def a(one, two, the_argument_function):
    if one in two:
        return the_argument_function
Run Code Online (Sandbox Code Playgroud)

我的 the_argument_function 看起来像这样:

def b(do_this, do_that):
    print "hi."
Run Code Online (Sandbox Code Playgroud)

以上两个都导入到文件“main_functions.py”中,我的最终代码如下所示:

print function_from_main(package1.a, argument, package2.b(do_this, do_that)
Run Code Online (Sandbox Code Playgroud)

来自“a”函数的“如果二分之一”有效,但“b”函数在传递给“function_from_main”时仍会执行,而无需等待来自“a”的检查以查看它是否确实应该执行。

我能做什么?

sha*_*uga 7

package2.b(do_this, do_that)是一个函数调用(函数名后跟括号)。相反,你应该只传递函数名称package2.b功能a

您还需要修改函数a,以便在满足条件时调用函数

# function a definition 
def a(one, two, the_argument_function, argument_dict):
    if one in two:
        return the_argument_function(**argument_dict)

def b(do_this, do_that):
    print "hi."

# function call for a
a(one, two, b, {'do_this': some_value, 'do_that': some_other_value}) 
Run Code Online (Sandbox Code Playgroud)