将Python函数作为参数传递而不执行它? [英] Passing Python Function as argument without executing it?
问题描述
我有这个功能:
def a(one, two, the_argument_function):
if one in two:
return the_argument_function
我的the_argument_function看起来像这样:
my the_argument_function looks something like this:
def b(do_this, do_that):
print "hi."
以上两项均导入到文件"main_functions.py"中,以使我的最终代码如下所示:
Both of the above are imported to a file "main_functions.py" for my ultimate code to look like this:
print function_from_main(package1.a, argument, package2.b(do_this, do_that)
"a"函数中的如果是二分之一"有效,但是当传递给"function_from_main"时,"b"函数仍会执行,而无需等待"a"中的检查是否应该执行.
The "if one in two" from "a"function works but "b"function still executes when being passed to "function_from_main" without waiting the check from "a" to see if it actually should execute.
我该怎么办?
推荐答案
package2.b(do_this,do_that)
是一个函数调用(函数名称后加括号).相反,您应该只传递函数名称 package2.b
函数 a
package2.b(do_this, do_that)
is a function call (a function name followed by parenthesis). Instead you should be passing only the function name package2.b
the function a
您还需要修改函数 a
,以便在满足条件时调用该函数
You will also need to modify function a
such that function be is called when the condition is satisfied
# 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})
这篇关于将Python函数作为参数传递而不执行它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!