谓词函数作为参数

VN1*_*992 0 python eclipse predicate python-3.x

我有一个函数将采用另一个函数,如果我作为参数传递的函数为真,则它会执行某些操作,如果为假,则它会执行其他操作,但是如何指定它以便作为参数传递的函数参数是一个返回布尔值的函数?

def a_function(function,value):
    if function(value) == True:
       do this
    else:
       do this
Run Code Online (Sandbox Code Playgroud)

但如果“函数”不是返回布尔值的函数,那么我的代码不起作用

spi*_*igo 5

使用 isinstance 的简单解决方案将起作用。在这里运行代码

http://codebunk.com/b/-JJzQlUmKV10CO5Lps_k

def fn(function,value):
    retval = function(value)
    if not isinstance(retval,bool):
       print("function did not return a bool")
       return None
    if retval:
        print "True"
    else:
        print "False"

fn(sum, [1,2,3])
fn(lambda x:True, [1,2,3])
Run Code Online (Sandbox Code Playgroud)

不久前,我写了一篇文章讨论 Guido 的多方法并使用它们对函数参数进行模式匹配。你可以在这里阅读这篇文章http://speak.codebunk.com/post/77084204957/pattern-matching-in-python